如何在没有端到端连接的石英环境中绘制线条?

时间:2012-05-16 18:32:19

标签: ios cgcontext cgpath

我正在跟踪视图中的触摸并在相关的“画布”中创建相应的行 层。这些点被累积到CGPathRef中并存储在touchesDidEnd的NSArray中 时间。

在drawLayer时,我按如下方式绘制当前路径和存储路径:

  // draw the current line:
    CGContextAddPath(ctx, path);
    CGContextStrokePath(ctx);
    NSLog(@"Canvas drawing path %@", path);

    // draw the stored lines
    for (NSMutableArray *arr in storedPaths) {
        CGMutablePathRef aPath = CGPathCreateMutable();
        // set up the path with the CGPointObjects
        NSLog(@"Canvas drawing stored path");
        BOOL inited = NO;
        for (CGPointObject *thePt in arr) {                    
            if (inited==NO) {
                CGPathMoveToPoint(aPath, NULL, [thePt.x floatValue],  [thePt.y floatValue]);
                //CGContextMoveToPoint(ctx, [thePt.x floatValue], [thePt.y floatValue]);
                inited = YES;
            }
            else {
                CGPathAddLineToPoint(aPath, NULL, [thePt.x floatValue], [thePt.y floatValue]); 
                //CGContextAddLineToPoint(ctx, [thePt.x floatValue], [thePt.y floatValue]); 
            }
        }
        CGContextAddPath(ctx, aPath);
        CGContextStrokePath(ctx);
        // didn't help connected problem
        //CGPathRelease(aPath);
    }

除了将第一行的结束点连接到下一行的起始点,而不是将它们保留为非触摸的单独行之外,它按预期工作。例: 用户绘制X但得到X,其中两个端点已连接。

CGClosePath看起来不像我想要的。任何建议都会非常感激。

2 个答案:

答案 0 :(得分:0)

如果每个偶数/奇数对都是一条线,那么用计数器替换'inited == NO'并使用'counter%2 == 0',这样对于偶数编号的点,它会移动到你想要的位置和奇数点,它连接前一点。可能更容易不使用快速枚举,而是使用旧式for循环。

    for (int i = 0; i < [arr count]; ++i) {
        CGPointObject *thePt = [arr objectAtIndex:i];                    
        if (i%2 == 0)
            CGPathMoveToPoint(aPath, NULL, [thePt.x floatValue],  [thePt.y floatValue]);
        else
            CGPathAddLineToPoint(aPath, NULL, [thePt.x floatValue], [thePt.y floatValue]); 
    }

答案 1 :(得分:0)

关于CGContextAddPath()的苹果文档非常不合适,但看起来它继续前面的路径,而不是添加新的子路径。因此,尝试构建一个CGMutablePathRef,用子路径填充它,然后将整个事物添加到上下文并进行描边。

,即将调用CGPathCreateMutable()移到外部循环之前,然后将调用移到CGContextAddPath()和CGContextStrokePath()之后。其余的可以保持不变。