Skip to content Skip to sidebar Skip to footer

Scale Rectf Object In Each Direction

It's possible to scale a RectF object of by an arbitrary factor in each direction? In practice i would resize of 2 factor a RectF (if RectF is 200X200 i would that he becomes 100x

Solution 1:

Try something like this:

privatevoidscale(RectF rect, float factor){
    float diffHorizontal = (rect.right-rect.left) * (factor-1f);
    float diffVertical = (rect.bottom-rect.top) * (factor-1f);

    rect.top -= diffVertical/2f;
    rect.bottom += diffVertical/2f;

    rect.left -= diffHorizontal/2f;
    rect.right += diffHorizontal/2f;
}

This is done without testing but I think it should work. This should keep the center in the same place and expand outward. All sides will be twice as big.

Solution 2:

Here my solution in Kotlin.

privatefun RectF.scale(factor: Float) {
    val oldWidth = width()
    val oldHeight = height()
    val rectCenterX = left + oldWidth / 2Fval rectCenterY = top + oldHeight / 2Fval newWidth = oldWidth * factor
    val newHeight = oldHeight * factor
    left = rectCenterX - newWidth / 2F
    right = rectCenterX + newWidth / 2F
    top = rectCenterY - newHeight / 2F
    bottom = rectCenterY + newHeight / 2F
}

The transformation should keep the center of the rect is the same coordinate (rectCenterX, rectCenterY) and set new width and height with the float scale factor. Have a nice day!

Post a Comment for "Scale Rectf Object In Each Direction"