Question

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 100x100)

Was it helpful?

Solution

Try something like this:

private void scale(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.

OTHER TIPS

Here my solution in Kotlin.

private fun RectF.scale(factor: Float) {
    val oldWidth = width()
    val oldHeight = height()
    val rectCenterX = left + oldWidth / 2F
    val rectCenterY = top + oldHeight / 2F
    val 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!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top