使用CGContext绘制时,线条消失

时间:2015-02-13 18:10:17

标签: objective-c cgcontext

我使用drawRect:和CGContext在自定义UIView类中绘制线条。对于添加的前几行,一切正常,但有时当我向要绘制的路径数组添加新路径(即:CGPoint到CGPoint)时,有可能先前绘制的一条线将消失。它为什么消失了?

- (void)drawRect:(CGRect)rect
{

    if ([_paths count]) {

        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetStrokeColorWithColor(context, [UIColor darkGrayColor].CGColor);
        CGContextSetLineWidth(context, 2.0f);

        // Drawing code
        for (NSDictionary * path in _paths){

            CGPoint startPoint = CGPointMake([path[@"startPointx"] floatValue], [path[@"startPointy"] floatValue]);
            CGPoint endPoint = CGPointMake([path[@"endPointX"] floatValue], [path[@"endPointY"] floatValue]);

            CGContextMoveToPoint(context, startPoint.x, startPoint.y); //start at this point
            CGContextAddLineToPoint(context, endPoint.x, endPoint.y); //draw to this point
        }

        CGContextStrokePath(context);
    }

}

编辑:

 NSMutableDictionary * newPath = [[NSMutableDictionary alloc] init];
 newPath[@"startPointx"] = [NSString stringWithFormat:@"%f",startPoint.x];
 newPath[@"startPointy"] = [NSString stringWithFormat:@"%f",startPoint.y];
 newPath[@"endPointX"] = [NSString stringWithFormat:@"%f",endPoint.x];
 newPath[@"endPointY"] = [NSString stringWithFormat:@"%f",endPoint.y];

 [_paths addObject:newPath];

---然后从superview中删除当前的_customPathView,实例化新的customPathView并添加路径,如下所示

[_customPathView setPaths:_paths];
[_scrollContentView insertSubview:_customPathView atIndex:0];
[_customPathView setNeedsDisplay];

应该注意的是,每次将新路径添加到数组中时,我都会从它的父视图中删除UIView,然后我使用新路径数组实例化一个新的UIView,以确保我得到一个新的UIView,传递了所有的路径。

在图像中看到线条首先从紫色点到灰色点,然后到白色点,但是当下一条线从白点绘制到下一个灰点时,前一行消失。

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

也许您需要将clearsContextBeforeDrawing设置为NO:

  

self.clearsContextBeforeDrawing=NO;