简体   繁体   中英

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)

}

在此处输入图片说明 Here is the stars image for you in case of you want to test. 在此处输入图片说明

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

To place the stars image in the centre of the CALayer , give the frame of the layer, ie

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

For any kind of CALayer , you need to define its frame explicitly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM