IOS图像拉伸解决方案

UIButton实现背景拉伸,即图片两端不拉伸中间拉伸的办法有如下两种:

第一种方法很简单而且使用性更广。做法就是直接拉伸想要setBackgroundImage的image,代码如下:

UIImage *image = [UIImage imageNamed:@"image.png"]; 
image = [image stretchableImageWithLeftCapWidth:floorf(image.size.width/2) topCapHeight:floorf(image.size.height/2)];

设置了左端帽之后,rightCapWidth = image.size.width - (image.leftCapWidth + 1); 也就是说图片中间的一像素用来拉伸。垂直方向同上。设置之后无论把image放到什么控件中都可以自动拉伸了。

 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];

第二种方法是在UIButton中加入一个UIImageView,拉伸imageView,然后将button的背景设为clearColor等等。把imageView放入button中,并且sendToBack,得到效果。代码如下:
 //刚才imageView拉伸的代码 

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;

//把imageView放入button中,并设置为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];

效果:


IOS图像拉伸解决方案,,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。