开发者

Fill 2D shape with rectangles

开发者 https://www.devze.com 2023-04-12 17:30 出处:网络
I am looking to fill an arbitrary 2D shape with rectangles, such as that the 2d shape becomes visible by looking at the composite image of the rectangles. The final result should look similar to image

I am looking to fill an arbitrary 2D shape with rectangles, such as that the 2d shape becomes visible by looking at the composite image of the rectangles. The final result should look similar to images produced by this application: http://www.shapecollage.com/ (No, I am not trying to copy said application, but I would like to offer similar functionality as part of a larger application).

I know from this SO question that an optimal solution to my problem might not exist, but a reasonably good result should be possible and would suffice for my means. So far I have tried the following two approaches based on the idea of a flood fill algorithm:

Approach 1

  1. Start with an arbitrary point in the shape, draw a rectangle at this point.

  2. Check a point to the right, bottom, left and top of the previous image, such as that the points checked correspond to the center of the next image if drawn side by side with the previous image

    // Example of finding new x-coordinate开发者_开发问答 for right move

    newCenter.x = oldCenter.x + oldWidth + newWidth;

  3. Check if the new center point is a) in the 2D shape and b) not inside an already drawn rectangle. If both conditions are fulfilled draw the rectangle and continue at step 2, otherwise don't do anything.

Approach 2

Same as Approach 1 but without the condition, that the rectangle's new center isn't allowed to be within a drawn rectangle. Instead a padding in all direction is added.

// Example of finding new x-coordinate for right move
newCenter.x = oldCenter.x + oldWidth + newWidth + padding;

Both approaches deliver extremely limited results and fail to completely fill the shape, though sometimes parts of the outline become visible with approach 1.

I am glad for any inputs, ideas or proven methods I could try to achieve a result similar to above examples. Thanks!


If you only need to closely (not perfectly) replicate the shape and not color, just put your shape onto an imaginary grid and then fill in its cells inside the shape with rectangles or pictures selected randomly. You may rotate them too so it's not too boring.


Try Weiler–Atherton clipping algorithm; I have used this for filling polygon with rectangular shapes. http://en.wikipedia.org/wiki/Weiler%E2%80%93Atherton_clipping_algorithm

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号