天天看點

ios開發 - iPhone圖檔拉伸:resizableImageWithCapInsets

原文位址:http://blog.csdn.net/lixing333/article/details/7589281

做一個溫度計的應用,需要一個圖,能夠根據輸入的資料将溫度計裡面的紅色圖檔拉伸。為了達到這個效果,使用了iOS5的函數:resizableImageCapInsets:(UIEdgeInsets)Insets。

其中Insets這個參數的格式是(top,left,bottom,right),從上、左、下、右分别在圖檔上畫了一道線,這樣就給一個圖檔加了一個框。隻有在框裡面的部分才會被拉伸,而框外面的部分則不會改變。比如(20,5,10,5),意思是下圖矩形裡面的部分可以被拉伸,而其餘部分不變。

ios開發 - iPhone圖檔拉伸:resizableImageWithCapInsets

據說stretchableImageWithLeftCapWidth:topCapHeight這個函數也能夠實作,但是在iOS5裡面建議不要使用這個函數。效果如下圖:

ios開發 - iPhone圖檔拉伸:resizableImageWithCapInsets

當修改了資料之後,變成這樣:

ios開發 - iPhone圖檔拉伸:resizableImageWithCapInsets

下面來看如何實作。

溫度計共由三張圖組成:

背景圖ThermometerBackground.png:

ios開發 - iPhone圖檔拉伸:resizableImageWithCapInsets

刻度圖ThermometerCalibration:

ios開發 - iPhone圖檔拉伸:resizableImageWithCapInsets

裡面的溶液Calibration:

ios開發 - iPhone圖檔拉伸:resizableImageWithCapInsets

首先将背景圖加入superview中,再将刻度圖和溶液圖加入背景圖中:(為簡化起見,一些不必要的代碼已經省略)

[plain]  view plain copy

  1. //将背景圖加入superview  
  2. UIImageView *thermometerBackground = [[UIImageView alloc] initWithFrame:THERMOMETER_FRAME];  
  3. [thermometerBackground setImage:[UIImage imageNamed:@"ThermometerBackground.png"]];  
  4. [self.view addSubview:self.thermometerBackground];  
  5. //将溶液圖加入背景圖  
  6. UIImageView *thermometer = [[UIImageView alloc]init];  
  7. [self.thermometerBackground addSubview:self.thermometer];  
  8. //将刻度圖加入背景圖  
  9. UIImageView *thermometerCalibration = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ThermometerCalibration.png"]];  
  10. [self.thermometerCalibration setFrame:CGRectMake(0, 10, thermometerBackground.frame.size.width, thermometerCalibration.image.size.height*thermometerBackground.frame.size.width/thermometerCalibration.frame.size.width)];  

[plain]  view plain copy

  1. [self.thermometerBackground addSubview:thermometerCalibration];  

然後,根據度數生成對應高度的image;  

[plain]  view plain copy

  1. UIImage* image = [UIImage imageNamed:@"Thermometer.png"];  
  2. UIEdgeInsets insets = UIEdgeInsetsMake(20, 0, 25, 0);  
  3. image = [image resizableImageWithCapInsets:insets];  
  4. int top = 10.00+(38.00-temperature)*20.00;  
  5. [self.thermometer setFrame:CGRectMake(0, top, self.thermometerBackground.frame.size.width, self.thermometerBackground.frame.size.height-top)];  

[plain]  view plain copy

  1. [self.thermometer setImage:image];  

在這裡,top這個變量就代表了根據度數計算出的溶液的高度。

這樣,當改變溫度temperature的大小時,隻要在viewWillAppear裡調用這段代碼,就能夠動态生成溫度計圖檔了。

ios6 方法已經改變  

(UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode

ios開發 - iPhone圖檔拉伸:resizableImageWithCapInsets

繼續閱讀