[英]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
. 我试图将
UIImage
的CGImage
为layer
的内容,然后将该layer
添加到view
的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
. 但似乎恒星的中心与
view
的origin
对齐。 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.