Monish
Monish

Reputation: 622

How to slicing image and stretchable in iOS

I need to stretch image right and left side centre half circle remain as it is. also need half circle in center

enter image description here

I have tried slicing concept and also tried below code

UIImage *image = self.imgBGBottom.image;
CGFloat capWidth =  floorf(image.size.width / 2) - 50;
CGFloat capHeight =  0;
UIImage *capImage = [image resizableImageWithCapInsets:
                     UIEdgeInsetsMake(capHeight, capWidth, capHeight, capWidth)];

[self.imgBGBottom setImage:capImage];

but it is not working for me

Please help me. Thanks in advance.

Upvotes: 6

Views: 3730

Answers (2)

Dipen Panchasara
Dipen Panchasara

Reputation: 13600

You are using function, use - (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight instead - (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets.

Set top, left cap to stretch your image as described in following code.

Objective-C

UIImage *image = [UIImage imageNamed:@"test"];

CGFloat capTop =  50;  // top cap to keep half round as is
CGFloat capLeft = 5; // To repeat it or stretch equally.
UIImage *capImage = [image stretchableImageWithLeftCapWidth:capLeft topCapHeight:capTop];

Swift

let image =  UIImage(named: "stretchableImage")

let capTop:Int =  50;  // top cap to keep half round as is
let capLeft:Int = 5; // To repeat it or stretch equally.
let capImage = image?.stretchableImage(withLeftCapWidth: capLeft, topCapHeight: capTop)

Alternet Solution

Same result can be achieved using following function as well.

Objective-C

UIImage *stretchedImage = [image resizableImageWithCapInsets:
                 UIEdgeInsetsMake(50, 50, 0, 50)];

Swift

var stretchedImage = image?.resizableImage(withCapInsets: UIEdgeInsets(top: 50, left: 50, bottom: 0, right: 50), resizingMode: .stretch) 

Note : Keep stretchable image as small as possible otherwise it will not stretch properly with smaller image container(ImageView, Button etc.). You can reduce height & width of your existing image.

Upvotes: 4

Jimmy
Jimmy

Reputation: 75

try this

UIImage *image = self.imgBGBottom.image;
CGFloat capWidth =  floorf(image.size.width / 2) - 50;
CGFloat capTop =  50;  //the value is determined by the half circle height,i guess it is 50 height
CGFloat capBottom = 0;
UIImage *capImage = [image resizableImageWithCapInsets:
                             UIEdgeInsetsMake(capHeight, capTop, capBottom, capWidth)];

[self.imgBGBottom setImage:capImage];

Upvotes: 0

Related Questions