JsW
JsW

Reputation: 1758

How to center a sublayer on another layer?

I drew something on a CAShapeLayer(). Now I want to put it on anther layer.

let layer = CAShapeLayer() // This is the layer I drew something on 
let imageView = UIImageView() //  The imageView I want to put the layer on 
imageView.layer.addSublayer(layer)

So how to align the center of the layer with the center of the image view? Thanks.

Upvotes: 0

Views: 3360

Answers (2)

dengApro
dengApro

Reputation: 4038

layer.frame = imageView.bounds  

It's OK.

To center a sublayer on anther layer, you could also check the anchorPointZ.

The anchor point for the layer’s position along the z axis.

The default value is to align the center of the layer to the center of the image view

If you need the layer of UIImageView resizes with its view .You need create a custom view class, and override layoutSublayersOfLayer

class CenterImageView: UIImageView {

    override func layoutSublayersOfLayer(layer: CALayer!) {
         super.layoutSublayersOfLayer(layer)
         layer.frame = self.bounds
    }
 }

Upvotes: 1

Kurt J
Kurt J

Reputation: 2603

layer.frame = imageView.bounds

Upvotes: 1

Related Questions