【问题标题】:Why doesn't CGPathIsRect work? Why doesn't CGPathContainsPoint work?为什么 CGPathIsRect 不起作用?为什么 CGPathContainsPoint 不起作用?
【发布时间】:2012-01-21 04:48:41
【问题描述】:

我正在制作一个 CGPoint 和一个 CGPathRef,然后尝试查找 CGPoint 是否在 CGPathRef 内。代码如下:

CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 0, 0);
CGPathMoveToPoint(path, NULL, 200, 0);
CGPathMoveToPoint(path, NULL, 200, 200);
CGPathMoveToPoint(path, NULL, 0, 200);
CGPathCloseSubpath(path);

CGPoint hitPoint = CGPointMake(77, 77);

if ( CGPathIsEmpty(path) )
    NSLog(@"Path Is Empty!");
else
{
    if ( CGPathIsRect(path, NULL) ) 
        NSLog(@"Path is a Rectangle!");
    else
    {
        NSLog(@"Path is NOT a Rectangle!");
        if (CGPathContainsPoint(path, NULL, hitPoint, FALSE)) // FALSE or TRUE - same result
            NSLog(@"Hit Point Inside: x=%f, y=%f", hitPoint.x, hitPoint.y);
        else
            NSLog(@"Hit Point Outside: x=%f, y=%f", hitPoint.x, hitPoint.y);
    }
}    

输出如下:

Path is NOT a Rectangle!
Hit Point Outside: x=77.000000, y=77.000000

路径显然是一个矩形,并且该点位于封闭路径内。请告诉我我在这里做错了什么。

【问题讨论】:

    标签: ios vector-graphics cgpath


    【解决方案1】:

    CGRectIsPath 仅在路径由 CGPathCreateWithRect 创建(带有不旋转或倾斜矩形的 transform 参数)或路径由 CGPathCreateMutable 创建且只有一个使用CGPathAddRect 添加矩形。

    它需要更多的工作来确定任意路径是否完全是一个矩形。路径可能包含实际上是直线的贝塞尔曲线段,或由连续直线段构成的边。

    如果您需要检测任意路径是否实际上只是一个矩形,则必须使用CGPathApply 自己进行。会很复杂。

    至于为什么您的点内测试不起作用:您需要使用CGPathAddLineToPoint 来创建矩形的边:

    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, 0);
    CGPathAddLineToPoint(path, NULL, 200, 0);
    CGPathAddLineToPoint(path, NULL, 200, 200);
    CGPathAddLineToPoint(path, NULL, 0, 200);
    CGPathCloseSubpath(path);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-07
      • 2019-08-06
      • 2016-07-05
      • 2011-08-06
      • 2013-01-18
      • 2012-07-09
      • 2019-10-31
      相关资源
      最近更新 更多