用CAShapeLayer画一条线

时间:2017-02-13 08:50:22

标签: ios swift cashapelayer

我想要显示这样的一行:

enter image description here

这是我的代码:

import UIKit

@IBDesignable
class ProgressView: UIView {

    let π = CGFloat(M_PI)
    var levelProgress: CGFloat = 0.0 {
        didSet {
            self.fgLayer.strokeEnd = levelProgress
        }
    }

    let bgLayer = CAShapeLayer()
    let fgLayer = CAShapeLayer()

    @IBInspectable var bgColor: UIColor = UIColor.black.withAlphaComponent(0.3) {
        didSet {
            configure()
        }
    }

    @IBInspectable var fgColor: UIColor = UIColor.white {
        didSet {
            configure()
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()

        setup()
        configure()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()

        setup()
        configure()
    }

    func setup() {
        bgLayer.lineWidth = 4.0
        bgLayer.fillColor = nil
        bgLayer.strokeEnd = 1
        layer.addSublayer(bgLayer)
        fgLayer.lineWidth = 4.0
        fgLayer.fillColor = nil
        fgLayer.strokeEnd = 0.0
        layer.addSublayer(fgLayer)
    }

    func configure() {
        bgLayer.strokeColor = bgColor.cgColor
        fgLayer.strokeColor = fgColor.cgColor
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        setupShapeLayer(shapeLayer: bgLayer)
        setupShapeLayer(shapeLayer: fgLayer)
    }

    private func setupShapeLayer(shapeLayer: CAShapeLayer) {
        shapeLayer.frame = self.bounds
        let linePath = UIBezierPath()
        linePath.move(to: self.frame.origin)
        linePath.addLine(to: CGPoint(x: self.frame.origin.x + self.frame.width, y: self.frame.origin.y))
        shapeLayer.path = linePath.cgPath
    }

}

但是在跑步之后,它没有显示任何东西。

1 个答案:

答案 0 :(得分:3)

问题是UIBezierPath的startPoint和endPoint设置错误。它应该是这样的:

private func setupShapeLayer(shapeLayer: CAShapeLayer) {
    shapeLayer.frame = self.bounds
    let linePath = UIBezierPath()
    linePath.move(to: CGPoint(x: 0, y: 0))
    linePath.addLine(to: CGPoint(x: self.frame.width, y: 0))
    shapeLayer.path = linePath.cgPath
}