【问题标题】:Getting really weird Error messages when trying to do HitDetection on a UIBezierPath尝试在 UIBezierPath 上执行 HitDetection 时收到非常奇怪的错误消息
【发布时间】:2013-08-13 03:33:33
【问题描述】:

我已添加此方法来检查 CGPoint 是否在 UIBezierPath

- (BOOL)isPointInPath:(CGPoint)point inShape:(BOOL)inShape {
CGContextRef context = UIGraphicsGetCurrentContext();
CGPathRef cgPath = path.CGPath;

CGPathDrawingMode mode = kCGPathStroke;
if (inShape) mode = kCGPathFill;

CGContextSaveGState(context);
CGContextAddPath(context, cgPath);

bool isHit = CGContextPathContainsPoint(context, point, mode);
CGContextRestoreGState(context);

return isHit;
}

path 是在头文件中声明的UIBezierPath

当我在 drawRect: 方法之外调用此方法时,我收到以下 4 条错误消息:

CGContextSaveGState: invalid context 0x0
CGContextAddPath: invalid context 0x0
CGContextPathContainsPoint: invalid context 0x0
CGContextRestoreGState: invalid context 0x0

但是当我在drawRect: 中调用它并且在绘图之后它可以工作。

为什么它在drawRect: 之外不起作用?这对我来说毫无意义。

【问题讨论】:

    标签: ios boolean drawrect cgcontext uibezierpath


    【解决方案1】:

    drawRect: 之外没有当前图形上下文(除非您创建一个),因此 contextNULL

    但是您不需要图形上下文来检查一个点是否在给定的形状内 通过UIBezierPath,您可以使用containsPoint: 方法。

    【讨论】:

    • 我通过调用 somebezierpath.contains(somecgpoint) 得到相同的上下文错误。
    【解决方案2】:

    我自己修复了它,我意识到 CGContext 使用起来很混乱,所以我改用 CGPath 并改用 CGPathContainsPoint 来代替它。

    【讨论】:

    • 您的问题是关于UIBezierPath,而不是CGPath,这就是为什么我在回答中推荐containsPoint:
    • 是的,这是一个很好的答案,但我找到了另一种方法,我可能会删除这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多