import java.awt.Point;
import java.awt.Rectangle;
import CH.ifa.draw.figures.RectangleFigure;
class SnapToGridFigure extends RectangleFigure {
private final static int GRID_SIZE_X = 25;
private final static int GRID_SIZE_Y = 25;
private int lostX, lostY;
public SnapToGridFigure() {
lostX = lostY = 0;
}
protected void basicMoveBy( int dx, int dy ) {
super.basicMoveBy( dx, dy );
snapToGrid();
}
public void basicDisplayBox( Point origin, Point corner ) {
super.basicDisplayBox( origin, corner );
snapToGrid();
}
private void snapToGrid() {
Rectangle box = displayBox();
int x = (int) box.getX();
int y = (int) box.getY();
if ( x % GRID_SIZE_X != 0 || y % GRID_SIZE_Y != 0 ) {
x = snapValueToGrid( x + lostX, GRID_SIZE_X );
y = snapValueToGrid( y + lostY, GRID_SIZE_Y );
displayBox( new Rectangle( x, y, (int) box.getWidth(), (int) box.getHeight() ) );
Rectangle after = displayBox();
lostX += box.getX() - after.getX();
lostY += box.getY() - after.getY();
}
}
private int snapValueToGrid( int value, int grid ) {
return value / grid * grid;
}
} |