Last Updated: October 18, 2020
·
13.18K
· cybersamx

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.

Picture

Solution

Create an PNG background image with rounded corners for the button in PhotoShop. See below:

Picture

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

UIKit Function Reference