Search code examples
iosuiviewmask

IOS: Touch outside layer mask but inside frame


I have an UIView with a layermask (smaller than its frame) that can receive touches. Now the thing is that i want to restrict those touches within the layer mask.

The mask is a rendered shape and not always a rectangle.

Do i have to do this with:

pointInside:withEvent:

or

hitTest:withEvent:

Or is there a better solution?


Solution

  • Solved it by creating a method that checks if there a solid or transparant pixel in the layer at a specific position:

    - (BOOL)isSolidPixel:(CGImageRef)image withXPosition:(int)xPos andYPosition:(int)yPos {
        if(xPos > CGImageGetWidth(image) || yPos > CGImageGetHeight(image))
            return NO;
    
        CFDataRef pixelData = CGDataProviderCopyData(CGImageGetDataProvider(image));
        const UInt8* data = CFDataGetBytePtr(pixelData);
    
        int pixelInfo = yPos * CGImageGetBytesPerRow(image) + xPos * 4;
    
        UInt8 alpha = data[pixelInfo];
    
        CFRelease(pixelData);
    
        if (alpha) 
            return YES;
    
        return NO;
    }