How do I implement a soft eraser stroke in a CGBitmapContext

我怕爱的太早我们不能终老 提交于 2019-12-30 05:28:09

问题


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 with varying line widths and alphas, but it appears that CGContextSetAlpha does not have an effect with kCGBlendModeClear.

How do I go about this?


回答1:


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.



来源:https://stackoverflow.com/questions/7800582/how-do-i-implement-a-soft-eraser-stroke-in-a-cgbitmapcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!