AsyncDisplayKit使用详解

来源:互联网 发布:淘宝企业店铺子账号 编辑:程序博客网 时间:2024/05/17 12:50

原文链接
AsyncDisplayKit的基本使用单元是node. ASDisplayNode是一个UIView层之上的封装,就像UIView是对CALayer的封装一样。跟View不一样的是,node是线程安全(比如uiview的操作就不是线程安全的,在非UI线程无法操作UIView)的,就是说你在非主线程对node进行初始化以及配置它们的层级操作都是安全的。

为了让用户界面平滑并且随时可以相应,app需要一秒渲染60帧, 这在iOS上是一个非常好的效果。这意味着主线程有1/60s的时间来放置各个frame,也就是说是在用16ms来执行所有的布局以及绘制代码。并且由于系统overhead,你那些改变布局的代码实际上只有10ms的时间来执行。

AsyncDisplayKit让你把image的解码,text sizing和渲染,以及其他的在费时的UI从左放置在了其他线程。(在使用view的时候,这些操作都只能放置在UI线程)

Nodes 作为view的替代

如果你非常熟悉view的使用方式,那么你已经知道如何使用nodes了。node的API跟UIView是非常相似的并且拥有一些便利。你也可以直接获得layer的属性,为一个view或者layer层级增加一个node,可以直接使用node.view或者node.layer。

AsyncDisplayKit的核心组件包括:

ASDisplayNode 与UIView对应 — 用来扩展生成定制的nodes

ASControlNode 类似UIControl —- 用来扩展生成buttons.

ASImageNode 类似UIImageView —– 异步的图像解码

ASTextode 类似UITextView —— 在TextKit上支持所有的富文本特性

ASTableView和ASCollectionView —— UITableView和UICollectionView的扩展来支持nodes.

你可以用这些相关的类来替代相应的UIKit中对应的类,这样会带来性能上的提高。(这是使用AsyncDisplayKit的原因,实际上是提供了六种高效的类供我们使用)

举个例子:

_imageView = [[UIImageView alloc] init];
_imageView.image = [UIImage imageNamed:@”hello”];
_imageView.frame = CGRectMake(10.0f, 10.0f, 40.0f, 40.0f);
[self.view addSubview:_imageView];
如果用node的方式:

_imageNode = [[ASImageNode alloc] init];
_imageNode.backgroundColor = [UIColor lightGrayColor];
_imageNode.image = [UIImage imageNamed:@”hello”];
_imageNode.frame = CGRectMake(10.0f, 10.0f, 40.0f, 40.0f);
[self.view addSubview:_imageNode.view];
虽然替换成node之后没有体现出ASDK的异步sizing和布局的功能,但是从性能上也提高了。因为这里使用了imageNode,这样会使得在解码hello.png图片的时候是在异步线程,并且很有可能是在另外一个CPU core上进行的。

(注意我们设置了一个预设的背景色给node,在屏幕上”holding its place” 直到real 内容出现。这样对图片是有效的,但是对text是无效的,因为人们总是希望text立即出现,但是允许图片加载有延时)

Button nodes

ASImageNode和ASTextNode都是继承于ASControlNode,所以可以把它们当成button一样使用。举例来说,现在我们准备添加一个shuffle button.

  • (void)viewDidLoad
    {
    [super viewDidLoad];
    // attribute a string
    NSDictionary attrs = @{
    NSFontAttributeName: [UIFont systemFontOfSize:12.0f],
    NSForegroundColorAttributeName: [UIColor redColor],
    };
    NSAttributedString string = [[NSAttributedString alloc] initWithString:@”shuffle”
    attributes:attrs];
    // create the node
    _shuffleNode = [[ASTextNode alloc] init];
    _shuffleNode.attributedString = string;
    // configure the button
    _shuffleNode.userInteractionEnabled = YES; // opt into touch handling
    [_shuffleNode addTarget:self
    action:@selector(buttonTapped:)
    forControlEvents:ASControlNodeEventTouchUpInside];
    // size all the things
    CGRect b = self.view.bounds; // convenience
    CGSize size = [_shuffleNode measure:CGSizeMake(b.size.width, FLT_MAX)];
    CGPoint origin = CGPointMake(roundf( (b.size.width - size.width) / 2.0f ),
    roundf( (b.size.height - size.height) / 2.0f ));
    _shuffleNode.frame = (CGRect){ origin, size };
    // add to our view
    [self.view addSubview:_shuffleNode.view];
    }
  • (void)buttonTapped:(id)sender
    {
    NSLog(@”tapped!”);
    }
    这样是符合我们的预期,但是button只有14/2的高,这样按钮会很难点。我们可以subclassing这个text节点,重写 -hitText:withEvent:,也可以用另外一种方式

CGFloat extendY = roundf( (44.0f - size.height) / 2.0f );
_shuffleNode.hitTestSlop = UIEdgeInsetsMake(-extendY, 0.0f, -extendY, 0.0f);
hitTextSlops对所有的节点都有效。

Custom nodes

对view进行Sizing或者layout一般情况下都是在主线程中完成的。 举个例子来说,一个custom UIView包含一个text view跟一个image view如下:

  • (CGSize)sizeThatFits:(CGSize)size
    {
    // size the image
    CGSize imageSize = [_imageView sizeThatFits:size];
    // size the text view
    CGSize maxTextSize = CGSizeMake(size.width - imageSize.width, size.height);
    CGSize textSize = [_textView sizeThatFits:maxTextSize];
    // make sure everything fits
    CGFloat minHeight = MAX(imageSize.height, textSize.height);
    return CGSizeMake(size.width, minHeight);
    }
  • (void)layoutSubviews
    {
    CGSize size = self.bounds.size; // convenience
    // size and layout the image
    CGSize imageSize = [_imageView sizeThatFits:size];
    _imageView.frame = CGRectMake(size.width - imageSize.width, 0.0f,
    imageSize.width, imageSize.height);
    // size and layout the text view
    CGSize maxTextSize = CGSizeMake(size.width - imageSize.width, size.height);
    CGSize textSize = [_textView sizeThatFits:maxTextSize];
    _textView.frame = (CGRect){ CGPointZero, textSize };
    }
    这并不是理想化的方式,我们计算了subviews两次—第一次是计算我们的view需要多大,第二次是在view中布局subview. 尽管示例中的这种布局运算消耗非常小,但是如果有text sizing的话,这样就可能会阻塞主线程。

我们可以改变这种情况通过手动的cacheing subview的sizes,但是这样会带来一些其他问题。仅仅只增加_imageSize或者_textSize变量是不够的,比如text发生了改变,我们需要重新计算它的大小。

我们可以把sizing计算放到后台,但是UIView并不允许这么做。
Node hierarchies

我们定制的node可能如下:

// perform expensive sizing operations on a background thread
- (CGSize)calculateSizeThatFits:(CGSize)constrainedSize
{
// size the image
CGSize imageSize = [_imageNode measure:constrainedSize];

// size the text node
CGSize maxTextSize = CGSizeMake(constrainedSize.width - imageSize.width,
constrainedSize.height);
CGSize textSize = [_textNode measure:maxTextSize];

// make sure everything fits
CGFloat minHeight = MAX(imageSize.height, textSize.height);
return CGSizeMake(constrainedSize.width, minHeight);
}

// do as little work as possible in main-thread layout
- (void)layout
{
// layout the image using its cached size
CGSize imageSize = _imageNode.calculatedSize;
_imageNode.frame = CGRectMake(self.bounds.size.width - imageSize.width, 0.0f,
imageSize.width, imageSize.height);

// layout the text view using its cached size
CGSize textSize = _textNode.calculatedSize;
_textNode.frame = (CGRect){ CGPointZero, textSize };
}
ASImageNode和ASTextNode,线程安全,可以在后台线程进行计算大小。 measure:方法跟sizeThatFits: 差不多,但是它额外的缓存了参数(constrainedSize)和结果(calculatedSize)。

定制Custom nodes的注意事项:

(1)nodes必须递归的计算所有的subNodes在calulateSizeThatFits:方法中。-measure方法只能再-calculateSizeThatFits:中被调用。

(2)Nodes需要把任何pre-layout计算放在calculateSizeThatFits:中

(3)nodes 必要的时候需要调用[self invaildateCalculatedSize],举个例子来说,ASTextNode在attributedString属性变化的时候就会invalidated他的calculated size.

比如,用node 来绘制一个彩虹效果:

@interface RainbowNode : ASDisplayNode
@end

@implementation RainbowNode

  • (void)drawRect:(CGRect)bounds
    withParameters:(id)parameters
    isCancelled:(asdisplaynode_iscancelled_block_t)isCancelledBlock
    isRasterizing:(BOOL)isRasterizing
    {
    // clear the backing store, but only if we’re not rasterising into another layer
    if (!isRasterizing) {
    [[UIColor whiteColor] set];
    UIRectFill(bounds);
    }

    // UIColor sadly lacks +indigoColor and +violetColor methods
    NSArray *colors = @[ [UIColor redColor],
    [UIColor orangeColor],
    [UIColor yellowColor],
    [UIColor greenColor],
    [UIColor blueColor],
    [UIColor purpleColor] ];
    CGFloat stripeHeight = roundf(bounds.size.height / (float)colors.count);

    // draw the stripes
    for (UIColor *color in colors) {
    CGRect stripe = CGRectZero;
    CGRectDivide(bounds, &stripe, &bounds, stripeHeight, CGRectMinYEdge);
    [color set];
    UIRectFill(stripe);
    }
    }

@end
realistic placeholders

Nodes 在render之前需要经过measurement以及display步骤。

使用ASDK,推荐的做法是当nodes的size被确定后,再添加到view的层级上。这样避免了布局在measurement完成之后进行改变,相反会让一个node在完全渲染之后才会再屏幕上出现。

一旦measurement 完成了,一个node可以精确的在屏幕上放置所有的subnodes–他们都是空白。最简单的方式来制造一个realistic placeholder是为你的node设置一个静态的背景色。这种效果会比一个generic placeholder image好,因为它会在内容加载的时候发生变化,并且对opaque images也正常。你也可以创建visually-appealing placeholder nodes,比如Paper里面的闪烁条的方式。
Working range

到目前位置,我们只讨论了异步的sizing.为了让很多内容在用户滑动的时候能够充分的被渲染,这要求了一种高级的触发显示。

如果你 app的内容是在一个scrollview中或者可以翻页,可以用working range的技术解决方案。一个working range controller 标记了可视区域范围,以及当前的显示的区域并且对优先对后面的内容进行了异步的渲染。当用户进行滚动的时候,一个或者两个之前滚动的内容会被保留,其他的会被清除掉。当在另一个方向上滚动的时候,the working range销毁了它的渲染队列,并且开始预渲染新方向的内容—因为设置了previous content的buffer,所以这个过程用户是不可见的。

AsyncDisplaykit 包含了一个generic working range controller,ASRangeController.

它的working range size 可以根据你的app来协调:如果你的nodes比较简单,一个iphone4都能维护一个大量的working range,但是如果重量级的nodes,它们应该是快速被修建的。

ASRangeController *rangeController = [[ASRangeController alloc] init];
rangeController.tuningParameters = (ASRangeTuningParameters){
.leadingBufferScreenfuls = 2.0f; // two screenfuls in the direction of scroll
.trailingBufferScreenfuls = 0.5f; // one-half screenful in the other direction
};
如果使用了working range,你需要根据不同的设备来设置tuning.

ASTableView

ASRangeController 管理了working ranges但是并没有显示内容。如果你的内容是在UITableView中被渲染的话,你可以使用ASTableView以及相应的custom nodes.ASTableView是UITableView的subclass让working range和 node-based cell协同作用。

0 0
原创粉丝点击