iOS圖片拉伸:resizableImageWithCapInsets
今天做了一個(gè)溫度計(jì)的應(yīng)用,需要一個(gè)圖,能夠根據(jù)輸入的數(shù)據(jù)將溫度計(jì)里面的紅色圖片拉伸。為了達(dá)到這個(gè)效果,使用了iOS5的函數(shù):resizableImageCapInsets:(UIEdgeInsets)Insets。
最近終于申請(qǐng)到蘋果開發(fā)者賬號(hào)!搞的好煩啊!給大家?guī)Ц@耍?/p>
想真機(jī)調(diào)試,上架應(yīng)用,將IPA打包給朋友用,或者申請(qǐng)開發(fā)者賬號(hào)的請(qǐng)聯(lián)系我!
真機(jī)調(diào)試有99個(gè)限制!
其中Insets這個(gè)參數(shù)的格式是(top,left,bottom,right),從上、左、下、右分別在圖片上畫了一道線,這樣就給一個(gè)圖片加了一個(gè)框。只有在框里面的部分才會(huì)被拉伸,而框外面的部分則不會(huì)改變。比如(20,5,10,5),意思是下圖矩形里面的部分可以被拉伸,而其余部分不變。
據(jù)說stretchableImageWithLeftCapWidth:topCapHeight這個(gè)函數(shù)也能夠?qū)崿F(xiàn),但是在iOS5里面建議不要使用這個(gè)函數(shù)。效果如下圖:
當(dāng)修改了數(shù)據(jù)之后,變成這樣:
下面來看如何實(shí)現(xiàn)。
溫度計(jì)共由三張圖組成:
背景圖ThermometerBackground.png:
刻度圖ThermometerCalibration:
里面的溶液Calibration:
首先將背景圖加入superview中,再將刻度圖和溶液圖加入背景圖中:(為簡(jiǎn)化起見,一些不必要的代碼已經(jīng)省略)
- //將背景圖加入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];
然后,根據(jù)度數(shù)生成對(duì)應(yīng)高度的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這個(gè)變量就代表了根據(jù)度數(shù)計(jì)算出的溶液的高度。
這樣,當(dāng)改變溫度temperature的大小時(shí),只要在viewWillAppear里調(diào)用這段代碼,就能夠動(dòng)態(tài)生成溫度計(jì)圖片了。






