【问题标题】:How to LIGHTLY erase drawn path in cgcontext?如何在 cgcontext 中轻轻擦除绘制的路径?
【发布时间】:2017-03-12 08:15:49
【问题描述】:

我设法在 CGContext 上实现擦除绘图

 UIImageView *maskImgView = [self.view viewWithTag:K_MASKIMG];
    UIGraphicsBeginImageContext(maskImgView.image.size);
    [maskImgView.image drawAtPoint:CGPointMake(0,0)];
    float alp = 0.5;

    UIImage *oriBrush = [UIImage imageNamed:_brushName];

    //sets the style for the endpoints of lines drawn in a graphics context
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGFloat eraseSize = oriBrush.size.width*_brushSize/_zoomCurrentFactor;

    CGContextSetLineCap(ctx, kCGLineCapRound);
    CGContextSetLineJoin(ctx, kCGLineJoinRound);
    CGContextSetLineWidth(ctx,eraseSize);
    CGContextSetRGBStrokeColor(ctx, 1, 1, 1, alp);
    CGContextSetBlendMode(ctx, kCGBlendModeClear);


    CGContextBeginPath(ctx);
    CGContextMoveToPoint(ctx, lastPoint.x,lastPoint.y);

    CGPoint vector = CGPointMake(currentPoint.x - lastPoint.x, currentPoint.y - lastPoint.y);
    CGFloat distance = hypotf(vector.x, vector.y);
    vector.x /= distance;
    vector.y /= distance;

    for (CGFloat i = 0; i < distance; i += 1.0f) {
        CGPoint p = CGPointMake(lastPoint.x + i * vector.x, lastPoint.y + i * vector.y);
        CGContextAddLineToPoint(ctx, p.x, p.y);
    }

    CGContextStrokePath(ctx);

    maskImgView.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    lastPoint = currentPoint;

问题是,这完全擦除了任何东西。此函数中设置的 alpha (CGContextSetRGBStrokeColor(ctx, 1, 1, 1, alp);) 似乎完全被忽略了。

我只想轻轻擦除,重复擦除将完全删除绘图。

有什么想法吗?

编辑:根据要求,我添加了有关此代码的更多详细信息: alp=_brushAlpha 是这个 ViewController 类中的一个属性。它的范围从 0.1 到 1.0。在测试时,我将其设置为 0.5。此绘图代码由平移手势识别器(更改状态)触发。它基本上是跟随手指(用手指绘制/擦除)。

【问题讨论】:

  • 你能不能告诉观众,alp resp 的价值是什么? _brushAlpha 是?但是,这个绘图代码在哪里?
  • 好的,我为代码添加了更多详细信息。

标签: ios objective-c alpha cgcontext erase


【解决方案1】:

您已将混合模式设置为清除。这忽略了笔触颜色。您应该稍微玩一下各种模式,但我怀疑您想要类似 sourceAtop 或 screen 的东西。详情请参阅CGBlendMode docs。

【讨论】:

  • 感谢您的建议。今晚我试试看。
  • 我设法使用 kCGBlendModeDestinationOut 使其工作。谢谢你指出了正确的方向。
【解决方案2】:

您在 UIView 中有一个名为 clearsContextBeforeDrawing 的标志。如果您将其设置为 YES,它将在每次抽奖之前将其清除。 根据文档

一个布尔值,用于确定是否应在绘制之前自动清除视图的边界。 设置为 YES 时,在调用 drawRect: 方法之前,绘图缓冲区会自动清除为透明黑色。此行为可确保在重绘视图内容时不会留下任何视觉伪影。如果视图的 opaque 属性也设置为 YES,则视图的 backgroundColor 属性不能为 nil,否则可能会出现绘图错误。此属性的默认值为 YES。 如果您将此属性的值设置为 NO,您有责任确保在您的 drawRect: 方法中正确绘制视图的内容。如果您的绘图代码已经经过高度优化,则将此属性设置为 NO 可以提高性能,尤其是在滚动期间,可能只需要重绘视图的一部分。

【讨论】:

  • 不确定如何使用 clearsContextBeforeDrawing,因为我没有使用 drawRect。我编辑了我的问题以添加更多详细信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-03
  • 2021-12-16
  • 2015-06-20
相关资源
最近更新 更多