1

I want to build a UIButton out of 3 images (A,B,C). A and C are stretchable components (depending on the button text) the middle part is fixed.

What is the best way to attach these images to one another? How can I be flexible in the implementation without specifying all origins and widths and so on... Is it necessary to have a surrounding rectangle?

4

3 回答 3

3

You need to stitch your images together in an image editor to create a single image. Then you'll load this image, and create a resizable version using the UIImage resizableImageWithCapInsets:resizingMode: method. You'll specify UIEdgeInsets that mirror the original widths of your two "end cap" images.

For the button itself you need to make this resizable image the background image of the button. It won't work as a foreground image.

   UIImage* bgImage = [[UIImage imageNamed:@"my_bg_image"] resizableImageWithCapInsets: UIEdgeInsetsMake(0, 10, 0, 10)];

   UIButton* b = [UIButton buttonWithType: UIButtonTypeCustom];
    [b setBackgroundImage: bgImage forState: UIControlStateNormal];
于 2013-05-28T23:01:10.343 回答
2

I've had to implement something like this recently. My strategy was to build what I wanted using UIView objects, and then write the created view to a UIImage.

I'd recommend:
-create a container view
-create UILabels for the button text, add to container view
-for labels A and C, sizeToFit them after they have their text, and then use that information to place the stretchable buttons in the view
-once the subviews are positioned, you'll probably want to reset the frame of your container view to make sure it is still correct.

once your view looks the way you want it, write it to an image using:

UIGraphicsBeginImageContextWithOptions(container.frame.size, NO, 0); //or YES if you have no opacity in your images
[container.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

-you can then set this as the image for your UIButton

于 2013-05-28T23:13:33.620 回答
1

The best way to do this is to put the 3 images into one file, and use resizableImageWithCapInsets:. See the doco here.

Here's a good tutorial on how to do this.

// Set the button background image
UIImage * buttonImage = [UIImage imageNamed:@"button_resizable.png"];
UIImage * resizableButtonImage = [buttonImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, 12, 0, 12)];
[button setBackgroundImage:resizableButtonImage forState:UIControlStateNormal];
于 2013-05-28T23:22:57.480 回答