Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stretch background image for UIButton

I got texture, which really shorter, than my UIButton.

I got this texture:

enter image description here

And i should create this button:

enter image description here

How should i stretch (not tile), this texture? Stretching in horizontal direction

Thnx

like image 380
Eugene Trapeznikov Avatar asked Sep 27 '12 14:09

Eugene Trapeznikov


3 Answers

From the example images you provided I'm pretty sure you're looking for UIImage's resizableImageWithCapInsets:

UIImage *originalImage = [UIImage imageNamed:@"myImage.png"];
UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);
UIImage *stretchableImage = [originalImage resizableImageWithCapInsets:insets];
[myButton setBackgroundImage:stretchableImage forState:UIControlStateNormal];
// the image will be stretched to fill the button, if you resize it.

The values in the UIEdgeInsets struct determine the margins you don't want to be stretched. Your left and right values could be about this wide:

enter image description here

The top and bottom values can be either 0 (if you don't want to resize the button vertically), or probably half of the total height.

like image 112
DrummerB Avatar answered Nov 11 '22 18:11

DrummerB


With Xcode 6 (and iOS7+ target) you can use slicing editor when working with images assets. Toggle slicing mode with Editor -> Show Slicing menu or press Show Slicing button when select specific image with editor (showed below).

Show Slicing button

Then you can select image for specific display scale and drag rules or edit insets values manually.

Rules

After that you can select this image in Interface Builder for UIButton Background Image (IB button's representation could look bad, but it should be OK when running).

My buttons look well (running iOS 7.1 simulator and iOS 8 device).

enter image description here

This Apple doc link could be helpful.

like image 44
Anton Gaenko Avatar answered Nov 11 '22 18:11

Anton Gaenko


By not tiling, I assume you can thus not use

- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets

The way to do what you want is to use:

UIGraphicsBeginImageContextWithOptions(newSize, NO, 0); // should be proportionally larger
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextDrawImage(context, (CGRect){{0,0}, newSize}, [yourImage CGImage]);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
like image 3
David H Avatar answered Nov 11 '22 16:11

David H