Masking circle segments in swift

隐身守侯 提交于 2019-12-01 11:37:46

问题


I'm creating a simple player app. There is a circle, that shows a progress of playing a song.

What is the best way to draw this circle in Swift and make a mask? I assume I can draw a 2 circles putting the width stroke to the thickness I want and without filling it. And the white one has to be masked according to some parameter. I don't have an idea, how to mask it in a proper way.


回答1:


I came up with this solution recently:

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)
    }
}

You just have to set a correct frame to it (via code or interface builder), and set the percent property.

This solution is not using mask or two circles, just two arcs, the first start at 12 o clock and goes to 2 * Pi * progress percent, and the other arc is drawn from the end of the previous arc to 12 o clock.

Important: the percent property has to be between 0 and 1!



来源:https://stackoverflow.com/questions/30554632/masking-circle-segments-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!