可见层的 (CAShapeLayer) 框架为零 - Swift

Visible layer's (CAShapeLayer) frame is zero - Swift

我试图在我的图层变换时追踪帧中的变化。动画是可见的,但不知何故我的帧 属性 在动画之前和之后设置为 (0,0,0,0)。我没有明确设置任何框架 属性 但我假设它是基于 BezierPath 设置的,因为你知道......该层是可见的并且可以工作所以它的框架不应该是(0,0,0,0 ).那么这是怎么回事?

//in viewDidLoad()
            var shapeLayer: CAShapeLayer!
            shapeLayer = CAShapeLayer()  
            shapeLayer.lineWidth = 2
            shapeLayer.strokeColor = UIColor.redColor().CGColor
            shapeLayer.fillColor = UIColor(red: 0.1, green: 0.3, blue: 0.6, alpha: 0.3).CGColor
            shapeLayer.path = UIBezierPath(ovalInRect: CGRectMake(40, 40, 100, 100)).CGPath
            println("\(shapeLayer.frame)")
            shapeLayer.contentsScale = UIScreen.mainScreen().scale
            view.layer.addSublayer(shapeLayer)

//when button is pressed
        shapeLayer.transform = CATransform3DMakeScale(2, 1, 3)
        println("\(shapeLayer.frame)")

我认为 masksToBounds 属性 设置为 false,所以不管你的层的框架是什么。另见此处: What UIView layer.masksToBounds is doing if set to YES?

您必须从路径中获取形状图层大小并将其设置为图层边界,然后将图层边界设置为图层框架。

shapeLayer.path = UIBezierPath(ovalInRect: CGRectMake(40, 40, 100, 100)).CGPath
let pathBounds = shapeLayer.path.boundingBoxOfPath
let shapeFrame = CGRect(x: pathBounds.origin.x , y: pathBounds.origin.y, width: 
pathBounds.size.width, height: pathBounds.size.height)
shapeLayer.bounds = shapeFrame
shapeLayer.frame  = shapeLayer.bounds