【问题标题】:Line disappears when drawing with CGContext使用 CGContext 绘制时线条消失
【发布时间】:2023-04-05 12:03:01
【问题描述】:

我正在使用 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,所有路径都在传递。

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

【问题讨论】:

  • 您的绘图代码看起来不错。你能包括你用来构造路径数组的东西吗?

标签: objective-c cgcontext


【解决方案1】:

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

self.clearsContextBeforeDrawing=NO;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多