Create custom UIButton using stretched image
Problem
You want to create a custom UIButton using a background image and which width can be easily resized with altering the background image.
Solution
Create an PNG background image with rounded corners for the button in PhotoShop. See below:
Use UIEdgeInsets to stretch the image. To allow the image to be stretched horizontally but preserve the corners under any button width, we need to define correct left and right edge insets.
UIEdgeInsetsMake(0.0f, 8.0f, 0.0f, 8.0f);
Apply the background to a button.
UIImage *image = [UIImage imageNamed:@"button_background_blue.png"];
UIEdgeInsets insets = UIEdgeInsetsMake(0.0f, 8.0f, 0.0f, 8.0f);
UIImage *stretchedImage = [image resizableImageWithCapInsets:insets];
[self.button setBackgroundImage:stretchedImage forState:UIControlStateNormal];
Make sure the button height matches the image height.
Reference
Written by Samuel Chow
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Objective-c
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#