Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Something I stumbled across while scratching my head over a similar problem is that CALayer uses <code>containsPoint:</code> when you send it <code>hitTest:</code></p> <p>Its default behaviour is to test against bounds, but we can override and get it to check the alpha channel, and just use CALayer's built in hit-testing to handle the rest:</p> <pre><code>- (BOOL) containsPoint:(CGPoint)p { return CGRectContainsPoint(self.bounds, p) &amp;&amp; !ImagePointIsTransparent(self.contents, p)) return YES; } </code></pre> <p>There's a discussion of testing for a single pixel's alpha at <a href="https://stackoverflow.com/questions/1042830/retrieving-a-pixel-alpha-value-for-a-uiimage">Retrieving a pixel alpha value for a UIImage</a></p> <p>This worked for my purposes:</p> <pre><code>static BOOL ImagePointIsTransparent(CGImageRef image, CGPoint p) { uint8_t alpha; CGContextRef context = CGBitmapContextCreate(&amp;alpha, 1, 1, 8, 1, NULL, kCGImageAlphaOnly); CGContextDrawImage(context, CGRectMake(-p.x, -p.y, CGImageGetWidth(image), CGImageGetHeight(image)), image); CGContextRelease(context); return alpha == 0; } </code></pre> <p>(If you're using <code>renderInContext:</code> to draw to the CALayer rather than setting its contents property, then it's going to be more complicated. This might be useful in that case: <a href="http://www.cimgf.com/2009/02/03/record-your-core-animation-animation/" rel="nofollow noreferrer">http://www.cimgf.com/2009/02/03/record-your-core-animation-animation/</a>)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload