How to use [UIImage resizableImageWithCapInsets:]

I would like to stretch an image of 170x50 size and show it as an image of 240x140 size. The original image is as follows:

enter image description here

I want to hold four corners and only stretch the central part. I am using the following code:

UIImage *originalImg = [UIImage imageNamed:@"ImageNamed"]; UIImage *resizeImg = [originalImg resizableImageWithCapInsets:UIEdgeInsetsMake(20 ,10, 10, 10)]; self.originalImgV.image = originalImg; self.resizedImgV.image = resizeImg; 

Both originalImgV and resizedImgV are set to the "fill aspect". I run it on a simulator, and the result:

enter image description here

I can not understand: resizedImgV has 2 arrows! Can someone tell me why and how can I use it correctly? Thanks

+6
source share
3 answers

Your problem is with the values ​​you pass to UIEdgeInsetsMake . Values: top, left, bottom, right. Due to the arrow in the upper left corner, you need to make sure that the left value is large enough to go from the left edge of the image to the right side of the arrow.

Given the image you posted, you need something like:

  UIEdgeInsetsMake(12, 32, 4, 4) 

BTW - the image should only be left + right + 1 pixel wide and top + bottom + 1 pixel high. Thus, your image should not be almost as big as it is.

+13
source

Use this function, you can resize UIImage with this function.

 + (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize { UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0); [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)]; UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; } 

Hope this helps you.

0
source

Stretching is processed in the vertical direction and then in the horizontal direction (or vice versa). Thus, provide upper and lower offsets, given the vertical direction that should not stretch, and the left and right offsets for the horizontal direction.

0
source

Source: https://habr.com/ru/post/953121/


All Articles