2015-05-31 22 views
1

我正在創建一個簡單的播放器應用程序。有一個圓圈,表示播放歌曲的進度。 enter image description hereswift中的遮蔽圓段

什麼是最好的方式來繪製這個圈子在斯威夫特,並製作一個面具?我想我可以繪製一個2圈,將寬度行程設置爲我想要的厚度並且不填充它。而白色的則必須根據某些參數進行遮蔽。我沒有一個想法,如何以適當的方式掩蓋它。

+0

可能重複的[如何使用CALayer創建一個圓?](http://stackoverflow.com/questions/28783494/how-do-i-create-a-circle-with-calayer) – Icaro

回答

1

最近,我想出了這個解決方案:

class CircularProgressView: UIView { 

    private let floatPi = CGFloat(M_PI) 
    private var progressColor = UIColor.greenColor() 
    private var progressBackgroundColor = UIColor.grayColor() 

    @IBInspectable var percent: CGFloat = 0.11 { 
     didSet { 
      setNeedsDisplay() 
     } 
    } 
    @IBInspectable var lineWidth: CGFloat = 18 

    override func drawRect(rect: CGRect) { 
     let context = UIGraphicsGetCurrentContext() 
     let origo = CGPointMake(frame.size.width/2, frame.size.height/2) 
     let radius: CGFloat = frame.size.height/2 - lineWidth/2 
     CGContextSetLineWidth(context, lineWidth) 
     CGContextMoveToPoint(context, frame.width/2, lineWidth/2) 
     CGContextAddArc(context, origo.x, origo.y, radius, floatPi * 3/2, floatPi * 3/2 + floatPi * 2 * percent, 0) 
     progressColor.setStroke() 
     let lastPoint = CGContextGetPathCurrentPoint(context) 

     CGContextStrokePath(context) 

     CGContextMoveToPoint(context, lastPoint.x, lastPoint.y) 
     CGContextAddArc(context, origo.x, origo.y, radius, floatPi * 3/2 + floatPi * 2 * percent, floatPi * 3/2, 0) 
     progressBackgroundColor.setStroke() 
     CGContextStrokePath(context) 
    } 
} 

你只需要設置一個正確的框架,以它(通過代碼或接口生成器),並設置%的財產。

該解決方案不使用蒙版或兩個圓圈,只有兩個圓弧,第一個從12點鐘開始,並達到2 * Pi *進度百分比,另一個圓弧從前一個圓弧的末端繪製到12時鐘。

重要提示:percent屬性必須介於0和1之間!

+0

酷!它工作得很好。謝謝! –