Pretty Buttons

Creating glossy, resizable buttons, like those on the incoming-call screen are quite easy, using the UIImage class to create "stretchable" images.

Screen shot of working buttons.

We merely provide a row and column of the image to be repeated in the vertical and horizontal directions, and set the image as the background image for a button. Whatever size we then make the button, the image stretches to fill the frame.

Visualization of stretching

Download the Xcode project.

Some Example Code

The Xcode project contains a larger example, but this will suffice, if you are just looking for a quick cut-and-paste solution.

// Load our image normally. UIImage *image = [UIImage imageNamed:@"button_green.png"]; // And create the stretchy version. float w = image.size.width / 2, h = image.size.height / 2; UIImage *stretch = [image stretchableImageWithLeftCapWidth:w topCapHeight:h]; // Now we'll create a button as per usual. UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.frame = CGRectMake(100.0f, 120.0f, 120.0f, 52.0f); [button setBackgroundImage:stretch forState:UIControlStateNormal]; [button setTitle:@"Penguin" forState:UIControlStateNormal]; [self.view addSubview:button];

Finis

Voilà! As simple as that. The image will fill the button, regardless of the button's frame.

Screen shot of the button in this article

Some Stretchable Images

Here are some free images for your project. (download: zipfile)

button_green.png button_red.png
button_green.png button_green@2x.png button_red.png button_red@2x.png
@2x @2x

Comments

Name:    (optional)
Comment: