3 Comments
User's avatar
palexdev's avatar

My implementation in Java with a few extensions: https://github.com/palexdev/rectcut-java

Expand full comment
vegasword's avatar

I'm learning UI programming from scratch, and this approach is indeed straightforward to start with. Thank you for the article! I would like to mention that for the cut functions, the shrinking mechanism is missing to counter the offset of the cut. Here are my functions as an example:

Rect CutLeft(Rect *rect, int length) {

int oldX = rect->x;

rect->x = min(rect->width, rect->x + length);

rect->width -= rect->x;

if (rect->width < 0) rect->width = 0;

return (Rect) { oldX, rect->y, rect->x, rect->height };

}

Rect CutRight(Rect* rect, int length) {

int oldWidth = rect->width;

rect->width = max(rect->x, rect->width - length);

rect->x += rect->width;

if (rect->x > width) rect->x = width;

return (Rect) { rect->width, rect->y, oldWidth, rect->height };

}

Rect CutTop(Rect* rect, int length) {

int oldY = rect->y;

rect->y = min(rect->height, rect->y + length);

rect->height -= rect->y;

if (rect->height < 0) rect->y = 0;

return (Rect) { rect->x, oldY, rect->width, rect->y };

}

Rect CutBottom(Rect* rect, int length) {

int oldHeight = rect->height;

rect->height = max(rect->y, rect->height - length);

rect->y += rect->height;

if (rect->y > height) rect->y = height;

return (Rect) { rect->x, rect->height, rect->width, oldHeight };

}

@palexdev did it in his Java implementation too

Expand full comment
Halt's avatar
Mar 1Edited

Not entirely sure what you mean by "counter" but the difference I see is that you are using a different type of rectangle, specifically one that uses X, Y and Width, Height (point+size). While as the rectangle I use is MinX, MinY, MaxX, MaxY (point+point).

I use this type of rectangle specifically because I then don't have to correct the width/height and also to be able to produce "inverted" rectangles (MinX > MaxX and/or MinY > MaxY). This inverted mode would result in negative width and height in your case. I do allow it so that I can "grow" an inverted rectangle as opposed to just cut.

This "hidden" feature is not explicitly mentioned in the article, but I do use it. Since the article I switched to X0, Y0 and X1, Y1 notation to make this clearer.

Expand full comment