How to add Stretchable UIImage in the CALayer.contents?

前端 未结 1 1042
野的像风
野的像风 2021-01-31 18:46

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\"] resizableImageW         


        
1条回答
  •  执笔经年
    2021-01-31 19:46

    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.

    0 讨论(0)
提交回复
热议问题