CALayer Position Contents to Bottom Left

Go To StackoverFlow.com

1

I am attempting to draw an image onto a CALayer. I only need an image, so I have created my later as follows:

CALayer *layer = [CALayer layer];

I add my image as follows:

NSImage *img = [[NSImage alloc] initWithContentsOfFile:@"path/to/img.png"];
[layer setContents:img];

This works, however it draws my images to fill the entire parent frame (stretching my image in the process).

Reading the docs, I found the following:

[layer setContentsGravity:@"kCAGravityBottomLeft"];

I am attempting to draw my image in the bottom left of the parent frame, however no matter what I do it draws my icon in the bottom center. Is there anyway to specify the bottom left?

2012-04-05 21:49
by Julio
How about setting the layer's frame size to match the image dimensions exactly, with an origin that positions it where you want relative to the view? Re the stretching, check out UIView's sizeToFit and sizeThatFits. But I haven't worked much with images, so this is mostly guesswork - Wienke 2012-04-06 00:21
@Wienke tried that first, and it seems to be insistent on remaining in the bottom center of the image - Julio 2012-04-09 14:26


0

Try this:

CALayer *layer = [CALayer layer];
layer.contentsGravity = kCAGravityBottomLeft;
layer.contents = (id) aCGImageRef;

Note that kCAGravityBottomLeft is declared as NSString and the contents property expects a CGImageRef.

2012-04-06 05:25
by Costique
While this works, it's only accomplishing what I've already done. Which is the issue - Julio 2012-04-09 14:26
So do you want the image to draw in the layer's bounds or in the layer's superlayer's bounds? If the latter, just set the layer's frame to its superlayer's bounds whenever the superlayer is resized. This is easier with NSViews because you can set autoresizing mask - Costique 2012-04-09 18:19
Ads