CATiledLayer
可以用来显示大尺寸的图片或者PDF文件,我们使用imageNamed
或者contentsOfFile
加载一张大尺寸的图片的时候,需要等待一段时间才能显示,看起来有一些延迟。CATiledLayer
可以将大尺寸的图片分割为小块小块的区域,异步分别加载需要显示的区域,只有在滑动加载查看新区域的时候,即将显示的新区域会有短暂的空白加载等待,避免了用户长时间等待。
CATiledLayer
在制作PDF阅读器或者地图类应用中肯定会有用武之地的。
创建一个基于UIView
的TiledView,这些为主要代码
#import "TiledView.h"
@interface TiledView ()
@property (nonatomic ,assign) CGPDFPageRef page;
@end
@implementation TiledView
+(Class)layerClass {
return [CATiledLayer class];
}
-(instancetype)initWithFrame:(CGRect)frame path:(NSString *)path completion:(void(^)(CGSize size))completion {
self = [super initWithFrame:frame];
if (self) {
NSURL *docURL = [NSURL fileURLWithPath:path];
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)docURL);
CGPDFPageRef page = CGPDFDocumentGetPage(pdf, 1);
self.page = page;
CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFCropBox);
CATiledLayer * layer = (CATiledLayer *)self.layer;
layer.levelsOfDetailBias = 5;
layer.bounds = pageRect;
int w = pageRect.size.width;
int h = pageRect.size.height;
int levels = 1;
while (w > 1 && h > 1) {
levels++;
w = w >> 1;
h = h >> 1;
}
layer.levelsOfDetail = levels;
[self setFrame:pageRect];
if (completion) {
completion(pageRect.size);
}
}
return self;
}
-(void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
CGContextDrawPDFPage(ctx, self.page);
}
使用过程:
#import "TiledViewController.h"
#import "TiledView.h"
@interface TiledViewController ()
@end
@implementation TiledViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIScrollView * scr = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
[self.view addSubview:scr];
NSString *path = [[NSBundle mainBundle] pathForResource:@"sf_muni" ofType:@"pdf"];
NSLog(@"%@", path);
TiledView * view = [[TiledView alloc] initWithFrame:self.view.bounds path:path completion:^(CGSize size) {
scr.contentSize = size;
}];
[scr addSubview:view];
}
![](https://img.haomeiwen.com/i1488056/b1da8186eb296a89.gif)
参考链接:
https://developer.apple.com/documentation/quartzcore/catiledlayer
http://www.jianshu.com/p/29cbc1744153
http://www.cocoachina.com/bbs/read.php?tid-31201-page-1.html
https://zhuanlan.zhihu.com/p/31323034
网友评论