Search code examples
swiftcalayercgimage

How to center a CGImage on a CALayer?


I was trying to set a UIImage's CGImage as a layer's content and then add the layer to a view's layer.
It's should be five stars at the center of the yellow view. That's what I want it to be.
But it seems the center of the stars is aligned with the origin of the view. What should I do to rectify it?

func putOnStars() {
    let rect = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
    rect.backgroundColor = .yellow
    view.addSubview(rect)

    let baseLayer = CALayer()
    baseLayer.contents = UIImage(named: "stars")?.cgImage
    baseLayer.contentsGravity = kCAGravityCenter
    rect.layer.addSublayer(baseLayer)

}

enter image description here Here is the stars image for you in case of you want to test. enter image description here


Solution

  • baseLayer doesn't have a defined frame so baseLayer.contentsGravity = kCAGravityCenter will work fine but it'll still be on the potision (0, 0).

    There are two possible solutions:

    1 : Make a frame of baseLayer that is identical to rect. Implement this code:

    baseLayer.frame = rect.frame
    

    2 : Set the position of baseLayer to the center of rect. Implement this code:

    baseLayer.position = rect.center