原文位址:http://blog.csdn.net/lixing333/article/details/7589281
做一個溫度計的應用,需要一個圖,能夠根據輸入的資料将溫度計裡面的紅色圖檔拉伸。為了達到這個效果,使用了iOS5的函數:resizableImageCapInsets:(UIEdgeInsets)Insets。
其中Insets這個參數的格式是(top,left,bottom,right),從上、左、下、右分别在圖檔上畫了一道線,這樣就給一個圖檔加了一個框。隻有在框裡面的部分才會被拉伸,而框外面的部分則不會改變。比如(20,5,10,5),意思是下圖矩形裡面的部分可以被拉伸,而其餘部分不變。
據說stretchableImageWithLeftCapWidth:topCapHeight這個函數也能夠實作,但是在iOS5裡面建議不要使用這個函數。效果如下圖:
當修改了資料之後,變成這樣:
下面來看如何實作。
溫度計共由三張圖組成:
背景圖ThermometerBackground.png:
刻度圖ThermometerCalibration:
裡面的溶液Calibration:
首先将背景圖加入superview中,再将刻度圖和溶液圖加入背景圖中:(為簡化起見,一些不必要的代碼已經省略)
[plain] view plain copy
- //将背景圖加入superview
- UIImageView *thermometerBackground = [[UIImageView alloc] initWithFrame:THERMOMETER_FRAME];
- [thermometerBackground setImage:[UIImage imageNamed:@"ThermometerBackground.png"]];
- [self.view addSubview:self.thermometerBackground];
- //将溶液圖加入背景圖
- UIImageView *thermometer = [[UIImageView alloc]init];
- [self.thermometerBackground addSubview:self.thermometer];
- //将刻度圖加入背景圖
- UIImageView *thermometerCalibration = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ThermometerCalibration.png"]];
- [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
- [self.thermometerBackground addSubview:thermometerCalibration];
然後,根據度數生成對應高度的image;
[plain] view plain copy
- UIImage* image = [UIImage imageNamed:@"Thermometer.png"];
- UIEdgeInsets insets = UIEdgeInsetsMake(20, 0, 25, 0);
- image = [image resizableImageWithCapInsets:insets];
- int top = 10.00+(38.00-temperature)*20.00;
- [self.thermometer setFrame:CGRectMake(0, top, self.thermometerBackground.frame.size.width, self.thermometerBackground.frame.size.height-top)];
[plain] view plain copy
- [self.thermometer setImage:image];
在這裡,top這個變量就代表了根據度數計算出的溶液的高度。
這樣,當改變溫度temperature的大小時,隻要在viewWillAppear裡調用這段代碼,就能夠動态生成溫度計圖檔了。
ios6 方法已經改變
(UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode