Aug 22, 2013

Custom iOS Components: Scaling Background Images


When developing custom components like buttons or tabs, there's often a need to have those components in variety of sizes for different views/purposes.

For example, one view might have two tabs and another one might have three tabs. Even though basic tab background is the same, it will often have borders or shadows at the sides which can't be stretched. That's why many developers come up with most common solutions:

a) Saving the same background in all required sizes
b) Saving background picture by parts (top/bottom/middle or left/right/middle) with further combining

Apple has actually very elegant single line solution for this problem. Let's say we are developing custom alert view and our background looks like this :

Red lines mark the area which can't be stretched due to color variations and rounded corners (40 pixels at the top and 25 pixels at left, right and bottom), but everything else inside is basically single solid color which can be resized as wanted.

Basically you just need to "tell" iOS which parts of picture should not be stretched. Let's assume image name is "alert_bg.png".

For iOS 5 and up the following method does the trick:

AlertBg = [[UIImage imageNamed@"alert_bg.png"resizableImageWithCapInsets:UIEdgeInsetsMake(];

For earlier iOS versions you should use slightly different version:

AlertBg = [[UIImage imageNamed@"alert_bg.png"stretchableImageWithLeftCapWidth25 topCapHeight40];

And combined universal solution:

if ([AlertBg respondsToSelector:@selector(resizableImageWithCapInsets:)])
    AlertBg = [[UIImage imageNamed@"alert_bg.png"resizableImageWithCapInsets:UIEdgeInsetsMake(];
    AlertBg = [[UIImage imageNamed@"alert_bg.png"stretchableImageWithLeftCapWidth25 topCapHeight40];


This approach is also great for saving space - you can store minimal size backgrounds for buttons, tabs, etc with further image expansion.


  1. Mobile app gives a look to business app. A perfectly designed website always attracts more visitors. Even the simple factors like font color, font size plays a great role in making a mobile app attractive. We provide experienced team of website designers that lay emphasis on such minute details while designing.

    Cado Magenge
    " iphone application development melbourne
    app development company
    web design and development company
    mobile apps development companies melbourne

  2. Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing..
    iOS App Development Company
    Android App Development Company

  3. I am expecting more interesting topics from you. And this was nice content and definitely it will be useful for many people.
    Sms marketing
    Text message marketing
    Fitness SMS