قالب وردپرس درنا توس
Home / IOS Development / ios – add UIImage to CALayer

ios – add UIImage to CALayer



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

You can simply add an image to the view layer simply by using the content :

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

If you want to add the image to its own layer, you can do it like this: [19659003] let myLayer = CALayer ()
la myImage = UIImage (called: "star") ?. cgImage
myLayer.frame = myView.bounds
myLayer.contents = myImage
myView.layer.addSublayer (myLayer)

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

  enter image description here

But as you can see, it looks pixelated. This is because UIImage is smaller than UIView so it scales to fill the view, which is by default what you do not specify otherwise.

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

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

In iOS, you may want to set the isGeometryFlipped property to true if you do something with top or bottom gravity, otherwise it will be the opposite of what you expect. (Only gravity is tilted vertically, not content rendered. If you have trouble reversing content, see this answer.)

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

kCAGravityResize

This is the default.

 enter image description here

kCAGravityResizeAspect

 enter image description here

kCAGravityResizeAspectFill kCAGravityResizeAspectFill

 enter image description here

kCAGravityTop

 enter image description here

kCAGravityBottom

]

 enter image description here

kCAGravityLeft

 enter image description here

kCAGravityRight [194559010] ] enter image desc ription here "/>

kCAGravityTopLeft

 Enter image description here

kCAGravityTopRight

[1945layoutimageRotation"/>

194 59006]

 enter image description here

kCAGravityBottomRight kCAGravityBottomRight [1969]  enter image description here


Source link