CATiledLayer


CATiledLayer

有些時候你可能需要繪制一個很大的圖片,常見的例子就是一個高像素的照片或者是地球表面的詳細地圖。iOS應用通暢運行在內存受限的設備上,所以讀取整個圖片到內存中是不明智的。載入大圖可能會相當地慢,那些對你看上去比較方便的做法(在主線程調用UIImage-imageNamed:方法或者-imageWithContentsOfFile:方法)將會阻塞你的用戶界面,至少會引起動畫卡頓現象。

能高效繪制在iOS上的圖片也有一個大小限制。所有顯示在屏幕上的圖片最終都會被轉化為OpenGL紋理,同時OpenGL有一個最大的紋理尺寸(通常是20482048,或40964096,這個取決於設備型號)。如果你想在單個紋理中顯示一個比這大的圖,即便圖片已經存在於內存中了,你仍然會遇到很大的性能問題,因為Core Animation強制用CPU處理圖片而不是更快的GPU(見第12章『速度的曲調』,和第13章『高效繪圖』,它更加詳細地解釋了軟件繪制和硬件繪制)。

CATiledLayer為載入大圖造成的性能問題提供了一個解決方案:將大圖分解成小片然后將他們單獨按需載入。讓我們用實驗來證明一下。

小片裁剪

這個示例中,我們將會從一個2048*2048分辨率的雪人圖片入手。為了能夠從CATiledLayer中獲益,我們需要把這個圖片裁切成許多小一些的圖片。你可以通過代碼來完成這件事情,但是如果你在運行時讀入整個圖片並裁切,那CATiledLayer這些所有的性能優點就損失殆盡了。理想情況下來說,最好能夠逐個步驟來實現。

清單6.11 演示了一個簡單的Mac OS命令行程序,它用CATiledLayer將一個圖片裁剪成小圖並存儲到不同的文件中。

清單6.11 裁剪圖片成小圖的終端程序

 

 1 #import 
 2 
 3 int main(int argc, const char * argv[])
 4 {
 5     @autoreleasepool{
 6//handle incorrect arguments
 7         if (argc < 2) {
 8             NSLog(@"TileCutter arguments: inputfile");
 9             return 0;
10         }
11 
12         //input file
13         NSString *inputFile = [NSString stringWithCString:argv[1] encoding:NSUTF8StringEncoding];
14 
15         //tile size
16         CGFloat tileSize = 256; //output path
17         NSString *outputPath = [inputFile stringByDeletingPathExtension];
18 
19         //load image
20         NSImage *image = [[NSImage alloc] initWithContentsOfFile:inputFile];
21         NSSize size = [image size];
22         NSArray *representations = [image representations];
23         if ([representations count]){
24             NSBitmapImageRep *representation = representations[0];
25             size.width = [representation pixelsWide];
26             size.height = [representation pixelsHigh];
27         }
28         NSRect rect = NSMakeRect(0.0, 0.0, size.width, size.height);
29         CGImageRef imageRef = [image CGImageForProposedRect:&rect context:NULL hints:nil];
30 
31         //calculate rows and columns
32         NSInteger rows = ceil(size.height / tileSize);
33         NSInteger cols = ceil(size.width / tileSize);
34 
35         //generate tiles
36         for (int y = 0; y < rows; ++y) {
37             for (int x = 0; x < cols; ++x) {
38             //extract tile image
39             CGRect tileRect = CGRectMake(x*tileSize, y*tileSize, tileSize, tileSize);
40             CGImageRef tileImage = CGImageCreateWithImageInRect(imageRef, tileRect);
41 
42             //convert to jpeg data
43             NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithCGImage:tileImage];
44             NSData *data = [imageRep representationUsingType: NSJPEGFileType properties:nil];
45             CGImageRelease(tileImage);
46 
47             //save file
48             NSString *path = [outputPath stringByAppendingFormat: @"_%02i_%02i.jpg", x, y];
49             [data writeToFile:path atomically:NO];
50             }
51         }
52     }
53     return 0;
54 }
View Code

這個程序將20482048分辨率的雪人圖案裁剪成了64個不同的256256的小圖。(256*256是CATiledLayer的默認小圖大小,默認大小可以通過tileSize屬性更改)。程序接受一個圖片路徑作為命令行的第一個參數。我們可以在編譯的scheme將路徑參數硬編碼然后就可以在Xcode中運行了,但是以后作用在另一個圖片上就不方便了。所以,我們編譯了這個程序並把它保存到敏感的地方,然后從終端調用,如下面所示:

1 > path/to/TileCutterApp path/to/Snowman.jpg

 

The app is very basic, but could easily be extended to support additional arguments such as tile size, or to export images in formats other than JPEG. The result of running it is a sequence of 64 new images, named as follows:

這個程序相當基礎,但是能夠輕易地擴展支持額外的參數比如小圖大小,或者導出格式等等。運行結果是64個新圖的序列,如下面命名:

Snowman_00_00.jpg
Snowman_00_01.jpg
Snowman_00_02.jpg
...
Snowman_07_07.jpg

既然我們有了裁切后的小圖,我們就要讓iOS程序用到他們。CATiledLayer很好地和UIScrollView集成在一起。除了設置圖層和滑動視圖邊界以適配整個圖片大小,我們真正要做的就是實現-drawLayer:inContext:方法,當需要載入新的小圖時,CATiledLayer就會調用到這個方法。

清單6.12演示了代碼。圖6.12是代碼運行結果。

清單6.12 一個簡單的滾動CATiledLayer實現

 1 #import "ViewController.h"
 2 #import 
 3 
 4 @interface ViewController ()
 5 
 6 @property (nonatomic, weak) IBOutlet UIScrollView *scrollView;
 7 
 8 @end
 9 
10 @implementation ViewController
11 
12 - (void)viewDidLoad
13 {
14     [super viewDidLoad];
15     //add the tiled layer
16     CATiledLayer *tileLayer = [CATiledLayer layer];
17     tileLayer.frame = CGRectMake(0, 0, 2048, 2048);
18     tileLayer.delegate = self; [self.scrollView.layer addSublayer:tileLayer];
19 
20     //configure the scroll view
21     self.scrollView.contentSize = tileLayer.frame.size;
22 
23     //draw layer
24     [tileLayer setNeedsDisplay];
25 }
26 
27 - (void)drawLayer:(CATiledLayer *)layer inContext:(CGContextRef)ctx
28 {
29     //determine tile coordinate
30     CGRect bounds = CGContextGetClipBoundingBox(ctx);
31     NSInteger x = floor(bounds.origin.x / layer.tileSize.width);
32     NSInteger y = floor(bounds.origin.y / layer.tileSize.height);
33 
34     //load tile image
35     NSString *imageName = [NSString stringWithFormat: @"Snowman_%02i_%02i", x, y];
36     NSString *imagePath = [[NSBundle mainBundle] pathForResource:imageName ofType:@"jpg"];
37     UIImage *tileImage = [UIImage imageWithContentsOfFile:imagePath];
38 
39     //draw tile
40     UIGraphicsPushContext(ctx);
41     [tileImage drawInRect:bounds];
42     UIGraphicsPopContext();
43 }
44 @end
View Code

 

 

圖6.12 用UIScrollView滾動CATiledLayer

當你滑動這個圖片,你會發現當CATiledLayer載入小圖的時候,他們會淡入到界面中。這是CATiledLayer的默認行為。(你可能已經在iOS 6之前的蘋果地圖程序中見過這個效果)你可以用fadeDuration屬性改變淡入時長或直接禁用掉。CATiledLayer(不同於大部分的UIKit和Core Animation方法)支持多線程繪制,-drawLayer:inContext:方法可以在多個線程中同時地並發調用,所以請小心謹慎地確保你在這個方法中實現的繪制代碼是線程安全的。

Retina小圖

你也許已經注意到了這些小圖並不是以Retina的分辨率顯示的。為了以屏幕的原生分辨率來渲染CATiledLayer,我們需要設置圖層的contentsScale來匹配UIScreenscale屬性:

1 tileLayer.contentsScale = [UIScreen mainScreen].scale;

 

有趣的是,tileSize是以像素為單位,而不是點,所以增大了contentsScale就自動有了默認的小圖尺寸(現在它是128128的點而不是256256).所以,我們不需要手工更新小圖的尺寸或是在Retina分辨率下指定一個不同的小圖。我們需要做的是適應小圖渲染代碼以對應安排scale的變化,然而:

1 //determine tile coordinate
2 CGRect bounds = CGContextGetClipBoundingBox(ctx);
3 CGFloat scale = [UIScreen mainScreen].scale;
4 NSInteger x = floor(bounds.origin.x / layer.tileSize.width * scale);
5 NSInteger y = floor(bounds.origin.y / layer.tileSize.height * scale);

 

通過這個方法糾正scale也意味着我們的雪人圖將以一半的大小渲染在Retina設備上(總尺寸是10241024,而不是20482048)。這個通常都不會影響到用CATiledLayer正常顯示的圖片類型(比如照片和地圖,他們在設計上就是要支持放大縮小,能夠在不同的縮放條件下顯示),但是也需要在心里明白。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



猜您在找
 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM