Making UIProgressView Rounded corners

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

I have created a UIProgressView with following properties

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


        
13条回答
  •  遇见更好的自我
    2021-02-07 14:59

    //Updated for swift 4

    import Foundation
    import UIKit
    
    class CustomHorizontalProgressView: UIView {
    var progress: CGFloat = 0.0 {
    
        didSet {
            setProgress()
        }
    }
    
    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 = self.frame.height / 2.0
        self.layer.borderColor = UIColor.gray.cgColor
        self.layer.borderWidth = 1.0
    
        let margin: CGFloat = 6.0
        var width = (self.frame.width - margin)  * progress
        let height = self.frame.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)
    
        UIColor.red.setFill()
        pathRef.fill()
    
        UIColor.clear.setStroke()
        pathRef.stroke()
    
        pathRef.close()
    
        self.setNeedsDisplay()
     }
    }
    

提交回复
热议问题