2017-02-13 101 views
1

我要顯示這樣一行:畫一條線與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 
    } 

} 

但運行後,它不會顯示任何東西。

+0

你們都設置代碼來創建行,但你有沒有添加爲uiview的子視圖層? –

+0

不,我已經添加了它。 – Khuong

回答

1

問題是設置錯誤的startPoint和endPoint UIBezierPath。它應該是這樣的:

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 
}