命中测试UIView子类的填充区域

时间:2012-08-17 15:16:31

标签: objective-c

我有一些UIView子类,我在drawRect中绘制UIBezierPaths。在添加这些视图的viewController中,我需要进行命中测试以查看bezier路径内是否发生了点击。我尝试在视图子类中创建一个UIBezierPath变量,然后对其进行测试。但是当然,偏移是完全错误的 - 我会在屏幕的顶角而不是在形状上点击。

有人能建议最好的方法吗?这有意义吗,还是应该添加一些代码?

谢谢, 詹姆斯

1 个答案:

答案 0 :(得分:2)

这是我的自定义三角视图。它比bezier路径简单得多,但我相信它应该工作相同。我还有一个基于alpha级别的测试类别,基于像素每像素,我用于带有alpha图层的UIImages。 (在这篇文章中Retrieving a pixel alpha value for a UIImage

- (void)drawRect:(CGRect)rect
{    
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextMoveToPoint(context, 0.0, 0.0);
    CGContextAddLineToPoint(context, rect.size.width, 0.0);
    CGContextAddLineToPoint(context, 0.0, rect.size.height);
    CGContextClosePath(context);

    CGContextSetFillColorWithColor(context, triangleColor.CGColor);
    CGContextFillPath(context);

    CGContextSaveGState(context);

    [self.layer setShouldRasterize:YES];
    [self.layer setRasterizationScale:[UIScreen mainScreen].scale];

}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    CGMutablePathRef trianglePath = CGPathCreateMutable();
    CGPathMoveToPoint(trianglePath, NULL, 0.0, 0.0);
    CGPathAddLineToPoint(trianglePath, NULL, self.frame.size.width, 0.0);
    CGPathAddLineToPoint(trianglePath, NULL, 0.0, self.frame.size.height);
    CGPathCloseSubpath(trianglePath);


    if (CGPathContainsPoint(trianglePath, nil, point, YES)) {
        CGPathRelease(trianglePath);
        return self;
    } else {
        CGPathRelease(trianglePath);
        return nil;
    }
}