自定义UIView子类中的CAShapeLayer中心

时间:2016-04-27 19:56:47

标签: ios swift uiview core-animation frame

我创建了一个自定义UIView子类。在其中,我创建了一个CAShapeLayer作为CAGradientLayer的掩码。我正在使用故事板和@IBDesignable在故事板中一切正常。这就是它看起来完美的样子:

enter image description here

当我在模拟器中运行应用程序时,它看起来不正常:

enter image description here

这是设置它的代码:

@IBDesignable
class ProgressView: UIView {

let progressLayer = CAShapeLayer()
let gradientLayer = CAGradientLayer()

override func layoutSubviews() {
    super.layoutSubviews()
    setup()
}

func setup() {

    // Setup progress layer.
    progressLayer.lineWidth = 3.0
    progressLayer.fillColor = nil
    progressLayer.strokeEnd = 1
    progressLayer.strokeColor = UIColor.blackColor().CGColor
    progressLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)

    let radius = CGFloat(self.frame.height / 2.5)
    let startAngle = CGFloat(-M_PI / 2)
    let endAngle = CGFloat(3 * M_PI / 2)
    let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)

    progressLayer.path = path.CGPath

    layer.addSublayer(progressLayer)


    // Setup gradient layer mask.
    gradientLayer.colors = [Constants.ColorPalette.teal.CGColor, Constants.ColorPalette.orange.CGColor, Constants.ColorPalette.pink.CGColor]
    gradientLayer.startPoint = CGPoint(x: 0.5, y: 0)
    gradientLayer.endPoint = CGPoint(x: 0.5, y: 1)
    gradientLayer.frame = self.frame
    gradientLayer.mask = progressLayer

    layer.addSublayer(gradientLayer)
}

.....

我尝试更改frames并使用awakeFromNibrequired init?(coder aDecoder: NSCoder)来设置视图,但似乎无效。我想在UIView子类中执行所有操作,而不是UIViewController

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用图层框而不是自己:

  let radius = CGFloat(layer.frame.height / 2.5)
  ....
  gradientLayer.frame = layer.frame