Covering a CALayer with a CGImage

250 Views Asked by At

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?

2

There are 2 best solutions below

0
tcurdt On BEST ANSWER

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.

1
Leo Chen On

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