Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 280
giozh Avatar asked Feb 04 '26 23:02

giozh


2 Answers

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.

like image 91
Toon Borgers Avatar answered Feb 07 '26 12:02

Toon Borgers


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!

like image 25
Jonathan Mercandalli Avatar answered Feb 07 '26 13:02

Jonathan Mercandalli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!