UIButton achieves background stretching, that is, there are two ways to do this without stretching between the two ends of the image:
The first method is simple and widely used. The method is to directly stretch the image for setBackgroundImage. The Code is as follows:
- UIImage * image = [UIImage imageNamed: @ "image.png"];
- Image = [image stretchableImageWithLeftCapWidth: flograding (image. size. width/2) topCapHeight: flograding (image. size. height/2)];
After the left-side cap is set, rightCapWidth = image. size. width-(image. leftCapWidth + 1); that is, one pixel in the middle of the image is used for stretching. The vertical direction is the same as above. After the settings, the image can be automatically stretched no matter what controls the image is placed in.
- UIImage * buttonImage = [UIImage imageNamed: @ "contact.png"];
- ButtonImage = [buttonImage stretchableImageWithLeftCapWidth: flolf (buttonImage. size. width/2) topCapHeight: flolf (buttonImage. size. height/2)];
- UIImage * buttonImageselected = [UIImage imageNamed: @ "contactselected.png"];
- ButtonImage = [buttonImage stretchableImageWithLeftCapWidth: flolf (buttonImage. size. width/2) topCapHeight: flolf (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 UIButton, stretch the imageView, and set the background of the button to clearColor. Put the imageView in the button and sendToBack to get the effect. The Code is as follows:
// Code of the Image view extension just now
- 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 in 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: