add UIImage in CALayer

只愿长相守 提交于 2019-11-27 10:41:17
Suragch

This is a general answer for the sake of future viewers. It is based on the question title rather than the details of the original question.

How to add a UIImage to a CALayer

You can add an image to a view's layer simply by using its contents property:

myView.layer.contents = UIImage(named: "star")?.cgImage
  • Note that the UIImage needs to be converted to a CGImage.

If you wish to add the image in its own layer, you can do it like this:

let myLayer = CALayer()
let myImage = UIImage(named: "star")?.cgImage
myLayer.frame = myView.bounds
myLayer.contents = myImage
myView.layer.addSublayer(myLayer)

Modifying the appearance

The above code produces a view like this. The light blue is the UIView and the dark blue star is the UIImage.

As you can see, though, it looks pixelated. This is because the UIImage is smaller than the UIView so it is being scaled to fill the view, which is the default it you don't specify anything else.

The examples below show variations on the layer's contentsGravity property. The code looks like this:

myView.layer.contents = UIImage(named: "star")?.cgImage
myView.layer.contentsGravity = kCAGravityTop
myView.layer.isGeometryFlipped = true

In iOS, you may want to set the isGeometryFlipped property to true if you are doing anything with top or bottom gravity, otherwise it will be the opposite of what you expect. (Only the gravity is flipped vertically, not the content rendering. If you are having trouble with the content being flipped, see this answer.)

There are two UIView examples below for every contentsGravity setting, one view is larger than the UIImage and the other is smaller. This way you can see the effects of the scaling and gravity.

kCAGravityResize

This is the default.

kCAGravityResizeAspect

kCAGravityResizeAspectFill

kCAGravityCenter

kCAGravityTop

kCAGravityBottom

kCAGravityLeft

kCAGravityRight

kCAGravityTopLeft

kCAGravityTopRight

kCAGravityBottomLeft

kCAGravityBottomRight

Related

it has to be

layer.contents = (id)[UIImage imageNamed:@"myImage.png"].CGImage;

You can only put a CGImage into a layer, not an UIImage directly.

I removed

 [layer setNeedsDisplay];

I do not know why, but it works!

You need to set the frame of the CALayer properly, because the default is CGRectZero.

myView.layer.contents = UIImage(named: "star")?.cgImage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!