-1

I have a CGImage that I want to show in a CALayer. Setting the content and the gravity to the bottom-left works like expected.

layer.contents = cgimage
layer.contentsGravity = .bottomLeft

enter image description here

Now I want center and cover the full layer. Using .center just shifts the content center to the bottom-left.

layer.contents = cgimage
layer.contentsGravity = .center

enter image description here

Only when I set the position to the center of the view it displays as expected.

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

enter image description here

But with gravity set to resize-aspect-fill nothing is shown at all - with the position set or not.

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?

tcurdt
  • 14,518
  • 10
  • 57
  • 72
  • You are not showing your real code. Show it. Where is the part where you set the layer's frame? Or the layer's bounds and position? Where is the part where you put the layer into the interface? How do you generate the image? Give all details needed to _reproduce_ the phenomena. Show your code if you want help. – matt Jan 19 '22 at 14:17

2 Answers2

0

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
Leo Chen
  • 327
  • 1
  • 8
  • Thanks for the answer. But that doesn't seem to be the case. (0,0) is at the bottom-left. PS: be aware this is about AppKit not UIKit - although they are very similar. – tcurdt Jan 19 '22 at 12:01
-1

Turns out for a contentGravity of type .resize and .resizeAspectFill the frame of a CALayer has to be explicitly set. For a .center or .bottomLeft you can get away without.

tcurdt
  • 14,518
  • 10
  • 57
  • 72