你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> IOS圖像拉伸解決方案

IOS圖像拉伸解決方案

編輯: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];

效果:


  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved