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:
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
Generating an Unsigned IPA iOS Application
Dynamic Uiimageview Size Within Uitableview
Get iOS Itunes App Store Id of an App Itself
Service Workers and iOS/Safari
Saving Coredata To-Many Relationships in Swift
Perform Push Segue After an Unwind Segue
Will iOS Wake Up the Terminated App If It's Registered with Location for Uibackgroundmodes
Button Tap and Long Press Gesture
Separation Between Header and First Cell -- in Plain Uitableview
How to Change Uibutton Title Color
Expanding and Collapsing Table View Cells in iOS
iOS Get Heart Rate from Apple Watch in Near Real Time
Swapping Child Views in a Container View
Right Aligned Uitextfield Spacebar Does Not Advance Cursor in iOS 7
How to Add My App to the Share Sheet Action