如何轻轻擦除 cgcontext 中绘制的路径?

How to LIGHTLY erase drawn path in cgcontext?

我设法在 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 是一个 属性 delcared 在此 ViewController class。它的范围从 0.1 到 1.0。在测试时,我将其设置为 0.5。此绘图代码由平移手势识别器(更改状态)触发。基本上是跟着手指走(draw/erase by finger)。

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

A Boolean value that determines whether the view’s bounds should be automatically cleared before drawing. When set to YES, the drawing buffer is automatically cleared to transparent black before the drawRect: method is called. This behavior ensures that there are no visual artifacts left over when the view’s contents are redrawn. If the view’s opaque property is also set to YES, the backgroundColor property of the view must not be nil or drawing errors may occur. The default value of this property is YES. If you set the value of this property to NO, you are responsible for ensuring the contents of the view are drawn properly in your drawRect: method. If your drawing code is already heavily optimized, setting this property is NO can improve performance, especially during scrolling when only a portion of the view might need to be redrawn.

您已将混合模式设置为透明。这忽略了描边颜色。您应该尝试一下各种模式,但我怀疑您想要 sourceAtop 或 screen 之类的东西。有关详细信息,请参阅 CGBlendMode docs