Stretch background image for UIButton

二次信任 提交于 2019-11-26 22:33:48

问题


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

I got this texture:

And i should create this button:

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

Thnx


回答1:


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:

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.




回答2:


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).

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

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).

This Apple doc link could be helpful.




回答3:


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;



回答4:


Use stretchableImageWithLeftCapWidth:topCapHeight: method.

Refer: https://github.com/boctor/idev-recipes/tree/master/StretchableImages




回答5:


Or using Stretchable Images:

UIImage* imgbkg =[[UIImage imageNamed: @"my_bkg_image.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:10];

[_button setBackgroundImage: imgbkg forState: UIControlStateNormal];

Use 0 if you don't want to stretch certain side.



来源:https://stackoverflow.com/questions/12623961/stretch-background-image-for-uibutton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!