How to add Stretchable UIImage in the CALayer.contents? How to add Stretchable UIImage in the CALayer.contents? ios ios

How to add Stretchable UIImage in the CALayer.contents?


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.