今天我們來一起學(xué)習(xí)UIImageView的用法,由名字可以知道,今天的這個視圖是用來顯示圖片的。
圖片是信息傳播的的一種重要方式,它相對于文字來講更加的直觀、生動、形象的展示信息,iOS的圖片類提供了很多的功能來滿足開發(fā)的需要。
首先,還是一樣的視圖類創(chuàng)建:
//父類是UIView,以后這句話就不加注釋了,茶哥非常喜歡用這種方式來創(chuàng)建視圖類(storyboard的使用除外)
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 100, 100)];
[self.view addSubview:imageView];

UIImageView.png
在這里使用三種方式來加載一張圖片:
first
UIImage *im = [UIImage imageNamed:@"tea.png"];
second
//這個 mainbundle 就是 當(dāng)前的可執(zhí)行app 的在根目錄下的絕對路徑
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"tea" ofType:@"png"];
UIImage *im = [UIImage imageWithContentsOfFile:imagePath];
third
/*這里的data是用本地的圖片路徑找到圖片后轉(zhuǎn)換來的,NSData是數(shù)據(jù)類,我們網(wǎng)絡(luò)請求下來的圖片
數(shù)據(jù)也可以用NSData接收*/
NSData *data = [NSData dataWithContentsOfFile:imagePath];
UIImage *im = [UIImage imageWithData:data];
第一種和第二種其實是使用的相同的原理加載圖片,即將圖片CaChe到內(nèi)存中,而第三種方式圖片會以數(shù)據(jù)的形式加載到系統(tǒng)中,而這個數(shù)據(jù)可以是本地轉(zhuǎn)換的,也可以是從網(wǎng)絡(luò)圖片中獲取的,所以我們的UIImageView不僅可以顯示本地圖片還可以顯示網(wǎng)絡(luò)圖片。
此外還有另外一個比較重要的屬性contentMode,這個屬性用來設(shè)置圖片的顯示方式。
//參數(shù)為UIViewContentMode枚舉類型
[imageView setContentMode:UIViewContentModeScaleToFill];
UIViewContentMode具體參數(shù)如下:
typedef NS_ENUM(NSInteger, UIViewContentMode) {
UIViewContentModeScaleToFill, //拉伸自適應(yīng)填滿
UIViewContentModeScaleAspectFit, //自適應(yīng)比例大小
UIViewContentModeScaleAspectFill, //原始尺寸
UIViewContentModeRedraw, //尺寸改變時重新繪制
UIViewContentModeCenter, //居中
UIViewContentModeTop, //置頂
UIViewContentModeBottom, //置底
UIViewContentModeLeft, //居左
UIViewContentModeRight, //居右
UIViewContentModeTopLeft, //居左上
UIViewContentModeTopRight, //居右上
UIViewContentModeBottomLeft, //居左下
UIViewContentModeBottomRight, //居右下
};
我們還可以添加一組圖片,讓我們的圖片動起來,類似于gif圖
//首先將所有的組圖放入一個數(shù)組中
UIImage *im1 = [UIImage imageNamed:@"tea1.png"];
UIImage *im2 = [UIImage imageNamed:@"tea2.png"];
UIImage *im3 = [UIImage imageNamed:@"tea3.png"];
NSArray *imArr = @[im1,im2,im3];
[imageView setAnimationImages:imArr];
//設(shè)定動畫時間
[imageView setAnimationDuration:2];
//設(shè)置播放次數(shù),0表示無限播放
[imageView setAnimationRepeatCount:0];
//開始播放
[imageView startAnimating];
//判斷是否正在播放動畫
if (imageView.isAnimating) {
NSLog(@"動畫正在播放");
}
//停止播放
[imageView stopAnimating];
以上便是UIImageView的使用,不難吧,想了解更多iOS相關(guān)知識,請繼續(xù)關(guān)注茶哥兒!
創(chuàng)造即永恒,喝茶去……