简体   繁体   English

用 CGImage 覆盖 CALayer

[英]Covering a CALayer with a CGImage

I have a CGImage that I want to show in a CALayer .我有一个CGImage想在CALayer中显示。 Setting the content and the gravity to the bottom-left works like expected.将内容和重力设置到左下角可以正常工作。

layer.contents = cgimage
layer.contentsGravity = .bottomLeft

在此处输入图像描述

Now I want center and cover the full layer.现在我想要居中并覆盖整个图层。 Using .center just shifts the content center to the bottom-left.使用.center只是将内容中心移动到左下角。

layer.contents = cgimage
layer.contentsGravity = .center

在此处输入图像描述

Only when I set the position to the center of the view it displays as expected.只有当我将 position 设置到视图的中心时,它才会按预期显示。

layer.contents = cgimage
layer.contentsGravity = .center
layer.position = CGPoint(x: view.frame.width/2, y: view.frame.height/2)

在此处输入图像描述

But with gravity set to resize-aspect-fill nothing is shown at all - with the position set or not.但是将重力设置为 resize-aspect-fill 时根本没有显示任何内容 - 无论是否设置了 position。

layer.contents = cgimage
layer.contentsGravity = .resizeAspectFill

I have the feeling that I missing something fundamental.我有一种感觉,我错过了一些基本的东西。

Why isn't the CGImage in the CALayer covering the full size and keeping the aspect ratio?为什么CALayer中的CGImage不覆盖全尺寸并保持纵横比?

I can show image fill.我可以显示图像填充。 I think ur calyer of view is not center in parent view.我认为您的视图不在父视图的中心。

    let view = UIView.init(frame: self.view.bounds)
    self.view.addSubview(view)
    view.layer.contents = UIImage.init(named:"ic_control_group_unselect_on")?.cgImage
    view.layer.contentsGravity = .resize

Turns out for a contentGravity of type .resize and .resizeAspectFill the frame of a CALayer has to be explicitly set.结果是.resize.resizeAspectFill类型的contentGravity必须显式设置CALayer的框架。 For a .center or .bottomLeft you can get away without.对于.center.bottomLeft ,您可以不用。

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

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