美文网首页
50行代码实现刮奖效果

50行代码实现刮奖效果

作者: 晚雪浓情 | 来源:发表于2017-02-13 16:35 被阅读32次

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

    涂层代码⬇️

    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<UITouch>, with event: UIEvent?)
        {
            layer.handle(with:touches.first!.location(in: view))
        }
        override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?)
        {
            layer.handle(with:touches.first!.location(in: view))
        }
        override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?)
        {
            layer.isFinished = true
        }
        override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?)
        {
            layer.isFinished = true
        }
    

    相关文章

      网友评论

          本文标题:50行代码实现刮奖效果

          本文链接:https://www.haomeiwen.com/subject/gyctwttx.html