Making UIProgressView Rounded corners

前端 未结 13 1676
旧巷少年郎
旧巷少年郎 2021-02-07 13:59

I have created a UIProgressView with following properties

progressView.progressTintColor = UIColor.appChallengeColorWithAlpha(1.0)
progressView.trac         


        
13条回答
  •  闹比i
    闹比i (楼主)
    2021-02-07 14:56

    Swift 4.2 version from Umair Afzal's solution

    class CustomHorizontalProgressView: UIView {
    
    var strokeColor: UIColor?
    
    var progress: CGFloat = 0.0 {
        didSet {
            setNeedsDisplay()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }
    
    func setup() {
        self.backgroundColor = UIColor.clear
    }
    
    override func draw(_ rect: CGRect) {
        super.draw(rect)
        setProgress()
    }
    
    func setProgress() {
    
        var progress = self.progress
        progress = progress > 1.0 ? progress / 100 : progress
    
        self.layer.cornerRadius = frame.size.height / 2.0
        self.layer.borderColor = UIColor.gray.cgColor
        self.layer.borderWidth = 1.0
    
        let margin: CGFloat = 6.0
        var width = (frame.size.width - margin)  * progress
        let height = frame.size.height - margin
    
        if (width < height) {
            width = height
        }
    
        let pathRef = UIBezierPath(roundedRect: CGRect(x: margin / 2.0, y: margin / 2.0, width: width, height: height), cornerRadius: height / 2.0)
    
        strokeColor?.setFill()
    
        pathRef.fill()
        UIColor.clear.setStroke()
        pathRef.stroke()
        pathRef.close()
    }
    }
    

    And to use it

    var progressView: CustomHorizontalProgressView = {
        let view = CustomHorizontalProgressView()
        view.strokeColor = UIColor.orange
        view.progress = 0.5
        return view
    }()
    

提交回复
热议问题