原始图片:
拉伸后图片:
具体代码,很简单:
UIImage *bgImage = [[UIImage imageNamed:@"search_edit_bg.png"] stretchableImageWithLeftCapWidth:2 topCapHeight:0]; // UIImage *tempImage = [[UIImage imageNamed:@"remind_tohome_btn.png"] stretchableImageWithLeftCapWidth:2 topCapHeight:0]; UIView *theView = [[UIView alloc] initWithFrame:frame]; theView.backgroundColor = [UIColor clearColor]; UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:theView.bounds]; bgImageView.image = bgImage; [theView addSubview:bgImageView]; [bgImageView release];
从第二个像素,依次复制向后拉伸。
另外:textfiled,垂直居中:
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
ok!
下面是网上copy的一段新的方法
2、(UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)
//方法介绍
- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets NS_AVAILABLE_IOS(5_0); // create a resizable version of this image. the interior is tiled when drawn.
- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode NS_AVAILABLE_IOS(6_0); // the interior is resized according to the resizingMode
//参数结构
typedef struct UIEdgeInsets {
CGFloat top, left, bottom, right; // specify amount to inset (positive) for each of the edges. values can be negative to 'outset'
} UIEdgeInsets;
//用法示例
UIImageView *ImageView=[[UIImageView alloc]init];
[ ImageView setFrame:CGRectMake(126.0, 80.2, 30.0, 20.0)];
UIEdgeInsets ed = {0.0f, 10.0f, 0.0f, 10.0f};
[ImageView setImage:[[UIImage imageNamed:@"xxx.png"]resizableImageWithCapInsets:ed]];
self.view addSubview:ImageView ];
//以上左10.0,右10.0,是左边10像素以内右边10像素以内不拉伸,中间拉伸。如果上下左右都有参数,就说明九宫格的四个角不拉伸,其他都拉伸