CAShapeLayer位置不正确

时间:2017-02-02 13:47:29

标签: ios swift cashapelayer

我在使用CAShapeLayer绘制圆圈时遇到问题。我有一个自定义视图MainLogoAnimationView代码如下:

import UIKit

class MainLogoAnimationView: UIView {

    @IBOutlet var customView: UIView!
    var redCircle: AnimationCircleView!


    // MARK: Object Lifecycle

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    func setup() {
        _ = Bundle.main.loadNibNamed("MainLogoAnimationView", owner: self, options: nil)?[0] as! UIView
        self.addSubview(customView)
        customView.frame = self.bounds
        let circleWidth = frame.size.width*0.25
        let yPos = frame.size.height/2 - circleWidth/2
        redCircle = AnimationCircleView(frame: CGRect(x: 10, y: yPos, width: circleWidth, height: circleWidth))
        redCircle.backgroundColor = UIColor.yellow
        addSubview(redCircle)
    }

    override func layoutSubviews() {
        super.layoutSubviews()

    }
}

在界面构建器中,我创建了浅蓝色UIView并选择了MainLogoAnimationView作为子视图。

AnimationCircleView就像这样:

import UIKit

class AnimationCircleView: UIView {

    // MARK: Object lifecycle

    var circleColor = UIColor.red.withAlphaComponent(0.5).cgColor {
        didSet {
            shapeLayer.fillColor = circleColor
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    let shapeLayer = CAShapeLayer()

    func setup() {
        let circlePath = UIBezierPath(ovalIn: frame)
        shapeLayer.path = circlePath.cgPath
        shapeLayer.fillColor = circleColor
        shapeLayer.frame = self.frame
        shapeLayer.backgroundColor = UIColor.gray.cgColor
        layer.addSublayer(shapeLayer)
    }

}

截图:

enter image description here

似乎CAShapeLayer框架不正确,红色圆圈也处于错误位置。它应该在黄色方块内。我在这做错了什么?任何指针都会非常感激!谢谢!

更新:

enter image description here

1 个答案:

答案 0 :(得分:2)

AnimationCircleView里面setup更改

shapeLayer.frame = self.frame

shapeLayer.frame = self.bounds

这应确保在黄色矩形内绘制灰色。

修改:

与上面的答案类似,更改

let circlePath = UIBezierPath(ovalIn: frame)

let circlePath = UIBezierPath(ovalIn: bounds)

将解决您的问题并在灰色区域内绘制圆圈。

CAShapeLayer帧是相对于其添加的视图的位置计算的,因此将其设置为等于帧,将CAShapeLayer添加到原点的ax和y位置偏移值在self.frame中传递的x和y。