必须是自定义的按钮类型
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *normal = [UIImage resizableImage:@"RedButton"];
UIImage *high = [UIImage resizableImage:@"RedButtonPressed"];
[button setBackgroundImage:normal forState:UIControlStateNormal];
[button setBackgroundImage:high forState:UIControlStateHighlighted];
#import <UIKit/UIKit.h>
@interface UIImage (Extension)
+ (UIImage *)resizableImage:(NSString *)name;
#import "UIImage+Extension.h"
@implementation UIImage (Extension)
/**
* 返回一张可以随意拉伸不变形的图片
*
* @param name 图片名字
*/
+ (UIImage *)resizableImage:(NSString *)name
{
UIImage *normal = [UIImage imageNamed:name];
CGFloat w = normal.size.width * 0.5;
CGFloat h = normal.size.height * 0.5;
return [normal resizableImageWithCapInsets:UIEdgeInsetsMake(h, w, h, w)];
}
@end