How do I implement a soft eraser stroke in a CGBitmapContext

前端 未结 1 1224
-上瘾入骨i
-上瘾入骨i 2021-01-03 16:36

I am trying to erase an image with my touch in iOS. By setting the blend mode to kCGBlendModeClear I am able to do this - but only with hard edges. I could draw my stroke

相关标签:
1条回答
  • 2021-01-03 17:08

    I would use a transparency layer compositing with kCGBlendModeDestinationOut (Da * (1 - Sa), Dc * (1 - Sa).) Something like this:

    CGPathRef pathToErase = ...; // The path you want erased
    // could also be an image or (nearly) anything else
    // that can be drawn in a bitmap context
    
    CGContextSetBlendMode(ctx, kCGBlendModeDestinationOut);
    CGContextBeginTransparencyLayer(ctx, NULL);
    {
        CGContextSetGrayFillColor(ctx, 0.0, 1.0); // solid black
    
        CGContextAddPath(ctx, pathToErase);
        CGContextFillPath(ctx);
        // the above two lines could instead be CGContextDrawImage()
        // or whatever else you're using to clear
    }
    CGContextEndTransparencyLayer(ctx);
    

    Note that you should also save and restore the gstate (CGContextSaveGState()/CGContextRestoreGState()) before/after the transparency layer to ensure that the blend mode and any other gstate changes do not persist.

    Note: This is brain-compiled and it's possible that transparency layers don't play nice with all blend modes. If so, try drawing the path/image into a second bitmap context, then drawing the contents of that context with the above blend mode.

    You can also experiment with other blend modes for different effects.

    0 讨论(0)
提交回复
热议问题