IOS圖像拉伸解決方案


UIButton實現背景拉伸,即圖片兩端不拉伸中間拉伸的辦法有如下兩種:

第一種方法很簡單而且使用性更廣。做法就是直接拉伸想要setBackgroundImage的image,代碼如下: 

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


設置了左端帽之后,rightCapWidth = image.size.width - (image.leftCapWidth + 1); 也就是說圖片中間的一像素用來拉伸。垂直方向同上。設置之后無論把image放到什么控件中都可以自動拉伸了。

  

  1. UIImage *buttonImage = [UIImage imageNamed:@"contact.png"];  
  2. buttonImage = [buttonImage stretchableImageWithLeftCapWidth:floorf(buttonImage.size.width/2) topCapHeight:floorf(buttonImage.size.height/2)];  
  3.   
  4. UIImage *buttonImageselected = [UIImage imageNamed:@"contactselected.png"];  
  5. buttonImage = [buttonImage stretchableImageWithLeftCapWidth:floorf(buttonImage.size.width/2) topCapHeight:floorf(buttonImage.size.height/2)];  
  6.   
  7. UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];  
  8. button.frame = CGRectMake(0024044);  
  9. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];  
  10. [button setBackgroundImage:buttonImageselected forState:UIControlStateHighlighted];  
  11. button.center = CGPointMake(160240);  
  12. [button setTitle:@"button" forState:UIControlStateNormal];  
  13. [button setTitle:@"buttonClick" forState:UIControlStateHighlighted];  
  14. [self.view addSubview:button];  


第二種方法是在UIButton中加入一個UIImageView,拉伸imageView,然后將button的背景設為clearColor等等。把imageView放入button中,並且sendToBack,得到效果。代碼如下:
 //剛才imageView拉伸的代碼  

  1. UIImageView *strechTest = [[UIImageyiView alloc] initWithImage:[UIImage imageNamed:@"contact.png"]];  
  2. [strechTest setContentStretch:CGRectMake(0.5f0.5f0.f0.f)];  
  3. CGRect frame = strechTest.frame;  
  4. frame.size.width += 100;  
  5. strechTest.frame = frame;  

 

  1. //把imageView放入button中,並設置為back  
  2.  UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];  
  3.  button1.frame = frame;  
  4.  button1.center = CGPointMake(160140);  
  5.  [button1 addSubview:strechTest];  
  6.  [button1 sendSubviewToBack:strechTest];  
  7.  [button1 setBackgroundColor:[UIColor clearColor]];  
  8.  [button1 setTitle:@"button" forState:UIControlStateNormal];  
  9.  [button1 setTitle:@"buttonClick" forState:UIControlStateHighlighted];  
  10.  [self.view addSubview:button];  


效果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM