How to add Stretchable UIImage in the CALayer.contents?
Asked Answered
P

1

21

I have a CALayer and I want to add to it a stretchable image. If I just do:

        _layer.contents = (id)[[UIImage imageNamed:@"grayTrim.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0.0, 15.0, 0.0, 15.0)].CGImage;

it won't work since the layers' default contentGravity is kCAGravityResize.

I've read that this could be accomplished using the contentsCenter but I cannot seem to figure out how exactly would I use that to achieve the stretched image in my CALayer.

Any ideas are welcome!

Horatiu

Phillane answered 31/7, 2012 at 20:13 Comment(0)
P
34

The response to this question is this one. Lets say you have a stretchable image which stretches only in width and has the height fixed (for simplicity sake).

The image is 31px width ( 15px fixed size - doesn't stretch -, 1px will be stretched)

Assuming your layer is a CALayer subclass your init method should look like this:

    - (id)init
{
    self = [super init];
    if (self) {
        UIImage *stretchableImage = (id)[UIImage imageNamed:@"stretchableImage.png"];
        self.contents = (id)stretchableImage.CGImage;

        self.contentsScale = [UIScreen mainScreen].scale; //<-needed for the retina display, otherwise our image will not be scaled properly

        self.contentsCenter = CGRectMake(15.0/stretchableImage.size.width,0.0/stretchableImage.size.height,1.0/stretchableImage.size.width,0.0/stretchableImage.size.height);
    }
    return self;
}

as per documentation the contentsCenter rectangle must have values between 0-1.

Defaults to the unit rectangle (0.0,0.0) (1.0,1.0) resulting in the entire image being scaled. If the rectangle extends outside the unit rectangle the result is undefined.

This is it. Hopefully someone else will find this useful and it will save some development time.

Phillane answered 13/8, 2012 at 4:23 Comment(2)
It is better to use the scale of the image.Grapefruit
The suggested solution will fail on iPhone 6 plus if no @3x variant of the image is present. It is better to use the scale property of the image. self.contentScale = strechableImage.scale Then it will work even if not all variants of the image (@2x @3x) are present.Grapefruit

© 2022 - 2024 — McMap. All rights reserved.