How to add Stretchable UIImage in the CALayer.contents?

时间秒杀一切 提交于 2019-12-02 17:35:58

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!