0

How can a bounding box be created for a UIImageView that is not a CGRect?

I would like to have objects in my view which should display images as well as detection collisions.

The issue is I would like these object to be whatever shape they are rather than fitting them into a CGRect and detecting collisions on areas which are inside the box but are nit the actual image.

How does one achieve this?

some_id
  • 29,466
  • 62
  • 182
  • 304

1 Answers1

1

This is a non-trivial problem. But the basics are a CGRect is a rectangle and a hit test inside of a rectangle is fairly easy to understand. However, you sound like you want a more complex shape. UIImageView displays an image. It does not have any idea about what shape you want to use for your collision test. So you are going to have to tell it.

One easy thing to do is to look at the alpha/transparent values of the display image to create a shape. So to answer the question is a point hitting an image we figure out the location of point in the image and return true if the alpha is greater than 0. If you do this you can create any image with a transparent background and the code will just work.

If that will not work for you then can can also run a hit test on a point and a polygon this post covers that in detail.

How can I determine whether a 2D Point is within a Polygon?

Community
  • 1
  • 1
madmik3
  • 6,975
  • 3
  • 38
  • 60
  • Awesome and smart idea. Thanks for this. It should work perfectly. This detects alpha within the ImageView itself right and not the alpha of a view behind this tested one? – some_id Mar 13 '11 at 21:48
  • yeah it should work. this shows you how to get the data from the UIImage http://stackoverflow.com/questions/448125/how-to-get-pixel-data-from-a-uiimage-cocoa-touch-or-cgimage-core-graphics – madmik3 Mar 13 '11 at 23:57
  • Is there a similar method in obj-c to java's PixelGrabber getPixel() ? – some_id Mar 14 '11 at 08:00