UIButton to achieve background stretching, that is, there are two ways to stretch the middle of the picture without stretching:
The first approach is simple and more versatile. The idea is to directly stretch the image you want to setbackgroundimage, with the following code:
- UIImage *image = [UIImage imagenamed:@ "Image.png"];
- image = [Image Stretchableimagewithleftcapwidth:floorf (image. Size. width/2) Topcapheight:floorf (Image. Size. height/2)];
After setting the left end cap, rightcapwidth = Image.size.width-(image.leftcapwidth + 1); That is, one pixel in the middle of the picture is used for stretching. Perpendicular to the same direction. After setting, the image can be automatically stretched regardless of what control it is placed in.
- UIImage *buttonimage = [UIImage imagenamed:@ "Contact.png"];
- Buttonimage = [Buttonimage Stretchableimagewithleftcapwidth:floorf (buttonimage. Size. width/2) Topcapheight:floorf (buttonimage. Size. height/2)];
- UIImage *buttonimageselected = [UIImage imagenamed:@ "Contactselected.png"];
- Buttonimage = [Buttonimage Stretchableimagewithleftcapwidth:floorf (buttonimage. Size. width/2) Topcapheight:floorf (buttonimage. Size. height/2)];
- UIButton *button = [UIButton buttonwithtype:uibuttontypecustom];
- Button. frame = CGRectMake (0, 0, 240, 44);
- [Button setbackgroundimage:buttonimage forstate:uicontrolstatenormal];
- [Button setbackgroundimage:buttonimageselected forstate:uicontrolstatehighlighted];
- Button. Center = cgpointmake (160, 240);
- [Button settitle:@ "button" forstate:uicontrolstatenormal];
- [Button settitle:@ "ButtonClick" forstate:uicontrolstatehighlighted];
- [self. View Addsubview:button];
The second method is to add a uiimageview to the UIButton, extrude the ImageView, and then set the button's background to Clearcolor, and so on. Put the ImageView into the button, and sendtoback, get the effect. The code is as follows:
Just ImageView stretched the code
- Uiimageview *strechtest = [[Uiimageyiview alloc] initwithimage:[uiimage imagenamed:@ "Contact.png"];
- [Strechtest Setcontentstretch:cgrectmake (0. 5f, 0. 5f, 0. F, 0. f)];
- CGRect frame = Strechtest. Frame;
- Frame. Size. Width + = 100;
- Strechtest. frame = frame;
- Put the ImageView into the button and set it to back
- UIButton *button = [UIButton buttonwithtype:uibuttontypecustom];
- Button1. frame = frame;
- Button1. Center = cgpointmake (160, 140);
- [Button1 addsubview:strechtest];
- [Button1 sendsubviewtoback:strechtest];
- [Button1 setbackgroundcolor:[uicolor Clearcolor]];
- [Button1 settitle:@ "button" forstate:uicontrolstatenormal];
- [Button1 settitle:@ "ButtonClick" forstate:uicontrolstatehighlighted];
- [self. View Addsubview:button];
Effect:
iOS image stretching solution