Stretch Background Image for Uibutton

Stretch background image for UIButton

From the example images you provided I'm pretty sure you're looking for UIImage's resizableImageWithCapInsets:

UIImage *originalImage = [UIImage imageNamed:@"myImage.png"];
UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);
UIImage *stretchableImage = [originalImage resizableImageWithCapInsets:insets];
[myButton setBackgroundImage:stretchableImage forState:UIControlStateNormal];
// the image will be stretched to fill the button, if you resize it.

The values in the UIEdgeInsets struct determine the margins you don't want to be stretched. Your left and right values could be about this wide:

Sample Image

The top and bottom values can be either 0 (if you don't want to resize the button vertically), or probably half of the total height.

Setting background image on UIButton stretches button even though contentMode is set to ScaleAspectFit

If you want the button to main its original size, use image instead of backgroundImage.

In case my assumption is wrong, and setting background image is causing the button to stretch, it's probably your constraints is not set-up properly.

How to avoid distort and stretch image in Custom UIButton while using vector image set?

Setting the contentMode on the button itself doesn't work for me, but setting it on the button's imageView does. From this Stackoverflow answer:

button.imageView?.contentMode = .scaleAspectFit

How to not stretch an image in UIButton

Have you tried setImage instead of setBackgroundImage?



Related Topics



Leave a reply



Submit