50行代码实现刮奖效果

发现最近经常要干旧貌换新颜的活。。

涂层代码⬇️

class LuckyCard:CALayer
{
    var point:CGPoint!{ didSet{ oldValue == nil || isFinished ? LuckyCard.drawingPath.move(to: point) : LuckyCard.drawingPath.addLine(to: point) } }
    
    var isFinished = false { didSet { isFinished ? drawingPathArr.append(LuckyCard.drawingPath) : () } }
    
    fileprivate lazy var drawingPathArr = [drawingPath]
    
    fileprivate static let drawingPath:UIBezierPath =
    {
        let path = UIBezierPath()
        path.lineWidth = 30
        path.lineCapStyle = .round
        return path
    }()
    
    private override init() { super.init() }
    
    convenience init(with rect:CGRect)
    {
        self.init()

        frame = rect
        backgroundColor = UIColor.clear.cgColor
        setNeedsDisplay()
    }
    
    required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
    
    override func draw(in ctx: CGContext)
    {
        UIGraphicsPushContext(ctx)
        
        //涂层一般也不会换颜色 就不暴露出去了 自定义在这改就行
        ctx.setFillColor(UIColor(red: 211/255, green: 211/255, blue: 211/255, alpha: 0.7).cgColor)
        ctx.fill(bounds)
        ctx.setBlendMode(.clear)
        
        for path in drawingPathArr{ path.stroke() }
        
        UIGraphicsPopContext()
    }
}

extension LuckyCard
{
    func handle(with point:CGPoint)
    {
        drawPoint = point
        isFinished = false
        setNeedsDisplay()
    }
}

调用代码⬇️

    fileprivate let layer = LuckyCard(with: UIScreen.main.bounds)
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        view.layer.addSublayer(layer)
    }
    
    override func touchesBegan(_ touches: Set, with event: UIEvent?)
    {
        layer.handle(with:touches.first!.location(in: view))
    }
    override func touchesMoved(_ touches: Set, with event: UIEvent?)
    {
        layer.handle(with:touches.first!.location(in: view))
    }
    override func touchesCancelled(_ touches: Set, with event: UIEvent?)
    {
        layer.isFinished = true
    }
    override func touchesEnded(_ touches: Set, with event: UIEvent?)
    {
        layer.isFinished = true
    }

你可能感兴趣的:(50行代码实现刮奖效果)