Date: 2021jul26
Update: 2025sep26
Language: Java
Q. Java: Grow/Shrink AWT Rectangle by percentage
A. Use the grow() member. As show in this full example:
import java.awt.Rectangle;
class Demo {
static void growByPercent(Rectangle rect, final float percent) {
final float factor = percent / 100f / 2f;
// Divide the percent by 100 to get a factor between 0 and 1
// Divide by 2 because grow() applies to both sides
final int xGrow = Math.round(rect.width * factor);
final int yGrow = Math.round(rect.height * factor);
rect.grow(xGrow, yGrow);
}
static void shrinkByPercent(Rectangle rect, final float percent) {
growByPercent(rect, -1 * percent);
}
public static final void main(String []args) {
final int x = 20;
final int y = 20;
final int width = 200;
final int height = 50;
Rectangle rect = new Rectangle(x, y, width, height);
growByPercent(rect, 10);
System.out.println("bigger rect=" + rect);
}
}
Output:
bigger rect=java.awt.Rectangle[x=10,y=17,width=220,height=56]