您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 第四章之 UIImageView 與 UIImage 完全指南

編輯:iOS 開發綜合

iOS App 裡到處都是圖片:背景、小圖示、Logo、按鈕。這些圖都以 UIImage 物件表示,但一定要有一個容器把它畫到螢幕上——那就是 UIImageView。兩者分工清楚:UIImage 管資料,UIImageView 管顯示。

一、UIImage:圖片資料的載體

UIImage 專門儲存圖片資料,支援多種格式,其中 PNG 是 iOS 預設最友善的格式(有 alpha 通道、壓縮無損, also 能被系統最佳化)。它可以從檔案、Quartz 影像物件或 raw data 建立,也提供多種混合模式與透明度的繪製方法。除了「代表一張圖」,UIImage 還能對像素做處理以產生不同效果,這部分屬於 Core Image 的範疇。

二、四種常見的載入方式

1. 從 bundle 載入(最常用)

[UIImage imageNamed:@"a.png"];

這個方法會自動快取,適合 Loading frequently-used 小圖。缺點是無法指定路徑。

2. 從 NSData 載入(讀資料庫時常用)

NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:extension];
NSData *imageData = [NSData dataWithContentsOfFile:filePath];
[UIImage imageWithData:imageData];

3. 從檔案路徑直接載入

NSString *path = [[NSBundle mainBundle] pathForResource:@"icon" ofType:@"png"];
UIImage *myImage = [UIImage imageWithContentsOfFile:path];

這個方法不會快取,每次呼叫都重新解碼。記憶體吃緊時反而更好控制,能避免 imageNamed 快取過多圖片導致的記憶體警告。

4. 從網路載入

NSURL *url = [NSURL URLWithString:@"https://up.2cto.com/2013/0702/20130702085459778.jpg"];
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:url]];

正式環境請勿在 main thread 用同步方式抓圖,會讓 UI 卡住;改用 NSURLSession 或 SDWebImage 這類套件。

三、UIImageView 的基本用法

UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 45.0, 300, 300)];
imageView.image = [UIImage imageNamed:@"a.png"];
[self.view addSubview:imageView];
[imageView release];

常用屬性:

  • image:要顯示的 UIImage。
  • contentMode:決定圖片如何適應 frame,例如 UIViewContentModeScaleAspectFit(等比縮放至放得下)或 ScaleAspectFill(填滿並裁切)。
  • clipsToBounds:搭配 Fill 使用,超出部分是否裁掉。
  • animationImages 與 animationDuration:可播放一連串圖片形成 GIF 動畫效果。

四、讓 UIImageView 能點擊

UIImageView 預設關閉使用者互動,要點擊必須先開啟再掛手勢:

UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
imgView.userInteractionEnabled = YES;   // 關鍵:預設是 NO

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]
                                        initWithTarget:self action:@selector(onClickImage)];
[imgView addGestureRecognizer:singleTap];
[singleTap release];
-(void)onClickImage {
    NSLog(@"imageview is clicked!");
}

如果這個 UIImageView 是從 Storyboard 拉出來的,別忘了在屬性檢查器裡把 User Interaction Enabled 打勾,否則手勢永遠不會觸發——這是新手最常卡住的地方之一。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved