今天做了一個溫度計的應用,需要一個圖,能夠根據輸入的資料將溫度計裡面的紅色圖片展開。為了達到這個效果,使用了iOS5的函數:resizableImageCapInsets:(UIEdgeInsets)Insets。
最近終於申請到蘋果開發人員帳號!搞的好煩啊!給大家帶福利了!
想真機調試,上架應用,將IPA打包給朋友用,或者申請開發人員帳號的請聯絡我!
真機調試有99個限制!
其中Insets這個參數的格式是(top,left,bottom,right),從上、左、下、右分別在圖片上畫了一道線,這樣就給一個圖片加了一個框。只有在框裡面的部分才會被展開,而框外面的部分則不會改變。比如(20,5,10,5),意思是矩形裡面的部分可以被展開,而其餘部分不變。
據說stretchableImageWithLeftCapWidth:topCapHeight這個函數也能夠實現,但是在iOS5裡面建議不要使用這個函數。效果如:
當修改了資料之後,變成這樣:
下面來看如何?。
溫度計共由三張圖組成:
背景圖ThermometerBackground.png:
刻度圖ThermometerCalibration:
裡面的溶液Calibration:
首先將背景圖加入superview中,再將刻度圖和溶液圖加入背景圖中:為簡化起見,一些不必要的代碼已經省略)
- //將背景圖加入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)];
- [self.thermometerBackground addSubview:thermometerCalibration];
然後,根據度數產生對應高度的image
- 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)];
- [self.thermometer setImage:image];
在這裡,top這個變數就代表了根據度數計算出的溶液的高度。
這樣,當改變溫度temperature的大小時,只要在viewWillAppear裡調用這段代碼,就能夠動態產生溫度計圖片了。