简体   繁体   English

如何在CALayer上居中CGImage?

[英]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 . 我试图将UIImageCGImagelayer的内容,然后将该layer添加到viewlayer
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 . 但似乎恒星的中心与vieworigin对齐。 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). baseLayer没有定义的框架,因此baseLayer.contentsGravity = kCAGravityCenter可以正常工作,但仍位于位置(0,0)。

There are two possible solutions: 有两种可能的解决方案:

1 : Make a frame of baseLayer that is identical to rect . 1:制作一个与rect相同的baseLayer框架。 Implement this code: 实现此代码:

baseLayer.frame = rect.frame

2 : Set the position of baseLayer to the center of rect . 2:将baseLayer的位置设置为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 要将stars image放置在CALayer的中心,请给出图层的frame ,即

    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. 对于任何种类的CALayer ,您都需要显式定义其frame

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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