如何移动/重绘CGPathRef?

时间:2013-11-01 08:08:09

标签: ios iphone objective-c core-graphics

我有一个应用程序,其中一个视图与MS Visio配置类似。您可以添加不同的节点(圆圈,从UIImage渲染),然后用线连接它们,以创建类似于树数据表示的东西。添加部分工作正常。

-(void) drawLineToCache{

   // Circle *dad;
   // Circle *kid; 
   //      Circle is a wrapper class for the nodes.. dad and kid are   
   //      private instances declared earlier in this paint view

//associatedPaths is a NSMutableArray that contains Line objects, 
//       which is simply a wrapper class with a CGPathRef
    [dad.associatedPaths addObject:self.selectedLine]; 
    [kid.associatedPaths addObject:self.selectedLine]; 

    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, dad.middlePoint.x, dad.middlePoint.y);
    CGPathAddLineToPoint(path, NULL, kid.middlePoint.x, kid.middlePoint.y);
    CGPathCloseSubpath(path);
    CGContextAddPath(cacheContext, path);
    CGContextSetStrokeColorWithColor(cacheContext,[UIColor blackColor].CGColor);
    CGContextStrokePath(cacheContext);
    CGPathRelease(path);

    CGRect dirtyRect = CGRectMake(dad.middlePoint.x-10, dad.middlePoint.y-10, 500, 400);
    [self setNeedsDisplayInRect:dirtyRect];

}

我现在想要做的是移动圈子并删除它们。由于圆圈是UIImageViews,只需更新框架/从子视图中删除它即可移动/删除它们。

然后为了更新它我尝试了:

//Ideally this should be implemented in touchesMoved, but I 
//thought it might be too much for the renderer.. 
// movingCircle is simply a reference to which circle needs to be updated 
// (the above kid/dad). I have been able to debug it to the point that the 
// associatedPath arrays contains the correct lines.. 
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    CGPoint touchLocation = [[touches anyObject] locationInView:self];

    for (Line *line in movingCircle.associatedPaths) {
        CGMutablePathRef path = CGPathCreateMutableCopy(line.path);
        CGPathMoveToPoint(path, NULL, line.parentNode.middlePoint.x, line.parentNode.middlePoint.y);
        CGPathAddLineToPoint(path, NULL, line.childNode.middlePoint.x, line.childNode.middlePoint.y);
        CGPathCloseSubpath(path);
        CGContextAddPath(cacheContext, path);
        CGContextSetStrokeColorWithColor(cacheContext,[UIColor blackColor].CGColor);
        CGContextStrokePath(cacheContext);
        CGPathRelease(path);


    }
    [self setNeedsDisplay];
    movingCircle = nil;
}

但它不起作用......我知道这只会画一条新线(而不是删除旧线),但是甚至不会这么做..我也不知道如何删除旧的...

我的问题是:如何对线条做同样的事情?我很乐意为每个圆圈存储数组中的每个路径,但即便如此,在访问路径后,如何更新它们?我需要画一个新的,并以某种方式删除旧的?或者我可以简单地更改该行的一个终点吗?

提前致谢! :)

1 个答案:

答案 0 :(得分:0)

将它们存储在可变数组中,只需替换需要更改的任何行。您可以考虑将变换存储并应用于每个变换,但这样会更复杂,并且可能不会产生如此清晰的结果。更新阵列中的路径后,只需重新绘制屏幕的受影响区域即可。

您可能还想使用bezier路径而不是CG路径(更明亮的API级别与您正在使用的图像视图相当)。