Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating pixel perfect standard UIBarButtonItem with custom image inside

I've been scratching my head over this for the past couple of hours. Is it possible to create a standard UIBarButtonItem with a custom image inside? All I want is the standard blue button, but with an image that represents preferences (a screwdriver or cog wheel that I'll create myself) inside of it. I'd rather not use Photoshop to do this, since I'd like every single pixel to be perfect and future proof, in case Apple releases even higher resolution iOS devices.

I've found a wonderful project on GitHub that includes every graphic element shipped with iOS, and I've extracted what appears to be the image Apple itself uses when creating standard UIBarButtonItems. Problem is, it can't be resized to the proper dimensions in a way that I know of. In case it's not possible to do what I want with code, then maybe someone can tell me how to use this image.

GitHub - UIKit-Artwork-Extractor

[email protected]

Thanks!

like image 311
wstr Avatar asked Jul 09 '11 13:07

wstr


2 Answers

Just create your image, in a single color (only the alpha channel is significant) and use initWithImage:style:target:action: with the UIBarButtonItemStyleBordered or UIBarButtonItemStyleDone style.

If you want a full-color image, you'll have to use the image you linked. The secret is to resize it by duplicating the "middle" column and row of pixels in the style of an Android 9-patch image, rather than by scaling the entire thing.

like image 185
Anomie Avatar answered Nov 18 '22 19:11

Anomie


Images like that are used by making them stretchable. Basically, you want only the middle of the image to be stretched when you resize the image, while the left and right cap should not be scaled, to avoid distortion.

UIImage *buttonImage = [UIImage imageNamed:@"UINavigationBarDefaultButton.png"];
UIImage *stretchableButtonImage = [buttonImage stretchableImageWithLeftCapWidth:5 topCapHeight:0];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage:stretchableButtonImage forState:UIControlStateNormal];

In your case however, why don't you just use a UIBarButtonItem with the UIBarButtonItemStyleDone or UIBarButtonItemStyleBordered as its style?

like image 41
omz Avatar answered Nov 18 '22 20:11

omz