Quote:
Originally Posted by wadheraswati
I have two UIImage objects drawn using core graphics. I want to check whether they intersect i.e. if one is touching the other or if one is overlapping the other. The thing I know is to check the CGRect but it takes rectangular bounds but if i have irregular shape image - circle or star shape image. It shows intersection as YES even when it is not actually intersecting on iPhone screen because of the rectangular bounds.
What I need to do is develop a game in which an object should get deleted if that is on the top of all objects otherwise not. For this I have the only idea of checking the intersection, nothings else. I could check the proper intersection of lines using beziers but unable to do it regarding images. Please help.
|
Approach 1:
The slow but accurate way to do it is to create an 8-bit mask for each image, then either composite them into an off-screen context or write code to byte-by-byte AND the pixels of the two images together, looking for non-zero results.
To make it faster, you would probably want to create the masks and the context during setup, and re-use them during game play.
Approach 2:
It would probably be possible to distill it down to packed bit arrays, and shift the bit arrays and and them together to lower the memory footprint to 1 bit per pixel and speed things up. That would be some pretty hairy code to write though. Shades of my days as an assembler programmer.
Approach 3:
For non-rotated shapes, and ignoring holes in your shapes, you could probably calculate the minimum and maximum x extent of opaque pixels for every strip of pixels in both images, and then check for overlaps in each strip of pixels. That would be reasonably fast, and very accurate. It would still be a lot of work to write however.
Approach 4:
If your shapes are static, you should be able to come up with a specific algorithm that's much faster. Checking for the intersection of 2 circles, for example, you can pre-calculate the square of the distance at which they intersect, and then compare the square of the object's distances. You could also break up your shapes into a series of smaller bounding rectangles and check for intersections of those.
I think approach 3 would probably be the best general-purpose approach for non-rotating shapes. You'd pre-build a table of strip extents for each shape, and could determine intersection with something like 4•image_height integer comparisions, where image height would be the height of the smaller of the images you were comparing.