IOS:触摸外层图层,但在框架内部

时间:2012-07-18 11:15:11

标签: ios uiview mask

我有一个 UIView ,它有一个可以接收触摸的图层掩码(小于它的帧)。 现在的问题是我想限制图层蒙版中的那些触摸。

蒙版是渲染的形状,并不总是矩形。

我必须这样做:

pointInside:withEvent:

hitTest:withEvent:

或者有更好的解决方案吗?

2 个答案:

答案 0 :(得分:8)

它有点老问题,但也许对某人有用:)

在你的观点.h文件中;

@interface CustomPhotoFrame : UIView {
  @protected
    CGPathRef borderPath;
}
@property (nonatomic, assign) CGPathRef borderPath;

并且,在您的.m文件中;

@synthesize borderPath;

- (void)setClippingPath:(CGPathRef)path 
{
    CGPathRelease(borderPath);
    borderPath = path;
    CGPathRetain(borderPath);
}  

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    return CGPathContainsPoint(borderPath, NULL, point, FALSE);
}

用你的方法;呼叫;

UIBezierPath *aPath = [UIBezierPath bezierPath];

// your path codes.. assume that its a circle;

aPath = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(centeredCircleRect)];

CGPathRef cgPath = CGPathCreateCopy(aPath.CGPath);
[self setClippingPath:cgPath];

现在,您的触控方式仅会检测您的触控是否处于圆圈遮罩视图中。

答案 1 :(得分:0)

通过创建一个方法来解决它,该方法检查特定位置的图层中是否存在实体或透明像素:

- (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;
}