Triangle UIView - Swift

前端 未结 5 1576
长情又很酷
长情又很酷 2020-12-05 06:43

So I\'m making a game in which I am dropping objects which have to be destroyed by a spike(triangle) at the bottom of the screen by a user.

I cannot work out how to

5条回答
  •  情话喂你
    2020-12-05 07:13

    I've modified the previous code a bit to add margin and fill color as inspectable and it works well with Swift4:

    import UIKit
    
    @IBDesignable
    class TriangleView : UIView {
        var _color: UIColor! = UIColor.blue
        var _margin: CGFloat! = 0
    
        @IBInspectable var margin: Double {
            get { return Double(_margin)}
            set { _margin = CGFloat(newValue)}
        }
    
    
        @IBInspectable var fillColor: UIColor? {
            get { return _color }
            set{ _color = newValue }
        }
    
        override init(frame: CGRect) {
            super.init(frame: frame)
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }
    
        override func draw(_ rect: CGRect) {
    
            guard let context = UIGraphicsGetCurrentContext() else { return }
    
            context.beginPath()
            context.move(to: CGPoint(x: rect.minX + _margin, y: rect.maxY - _margin))
            context.addLine(to: CGPoint(x: rect.maxX - _margin, y: rect.maxY - _margin))
            context.addLine(to: CGPoint(x: (rect.maxX / 2.0), y: rect.minY + _margin))
            context.closePath()
    
            context.setFillColor(_color.cgColor)
            context.fillPath()
        }
    }
    

提交回复
热议问题