首页 > 解决方案 > 如何在 CGContext 中擦除自定义形状(不是矩形)

问题描述

我正在尝试在 iOS中实现类似刮刮乐的效果。基本效果是通过 using 实现的clear(_rect: CGRect),但是如何擦除自定义形状而不是矩形?
这是我的代码

class ImageMaskView: UIView {
    var image  = UIImage(named: "maskL")
    
    var line = [CGPoint ]()

    override func draw(_ rect: CGRect) {
        guard let context = UIGraphicsGetCurrentContext() else {return}
        
        image?.draw(at: CGPoint(x: 0, y: 300))
        
//     erase
            line.forEach { (position) in
//                print(position)
                let rect = CGRect(x: position.x,y:position.y,width:50,height:50)
                    context.clear(rect)
            }
    }
        
        
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
            guard let position = touches.first?.location(in: nil) else{return }
            print(position)
            line.append(position)
            setNeedsDisplay()

        }
}

也许我可以建立一个自定义功能clear?无论如何,如果你能给我一些建议,我将不胜感激

标签: iosswiftcore-graphics

解决方案


你试过 UIBezierPath 吗?您绝对可以使用 UIBezierPath 来构建自定义形状。但我不是 100% 确定如何清除而不是在上下文中绘制这条路径。尝试这样的事情:

let starPath: UIBezierPath = UIBezierPath()
starPath.move(to: CGPoint(x: 45.25, y: 0))
starPath.addLine(to: CGPoint(x: 61.13, y: 23))
starPath.addLine(to: CGPoint(x: 88.29, y: 30.75))
starPath.addLine(to: CGPoint(x: 70.95, y: 52.71))
starPath.addLine(to: CGPoint(x: 71.85, y: 80.5))
starPath.addLine(to: CGPoint(x: 45.25, y: 71.07))
starPath.addLine(to: CGPoint(x: 18.65, y: 80.5))
starPath.addLine(to: CGPoint(x: 19.55, y: 52.71))
starPath.addLine(to: CGPoint(x: 2.21,  y: 0.75))
starPath.addLine(to: CGPoint(x: 29.37, y: 23))
starPath.close();
context.setBlendMode(.destinationOut)
context.setFillColor(UIColor.clear.cgColor)
starPath.fill()

另外,不要忘记将视图的不透明设置为 false。


推荐阅读