圆角的处理
来自 <code> AsyncDisplayKit </code>的一个Deomo <code>SocialAppLayout</code> 这是一个 类似新浪微博,app的布局单页面。其中头像是圆角的,我们都知道,如果,使用layer来处理圆角,性能肯定有损耗。接下来,我们看看 SocialAppLayout 怎么做的。
有兴趣的可以从git上下载代码看看。
// User pic 头像Node 如果不懂 node 可以翻看我之前的博客,不过没所谓,可以忽略,我们重点看圆角。
_avatarNode = [[ASNetworkImageNode alloc] init];
///此处为设置圆角
_avatarNode.imageModificationBlock = ^UIImage *(UIImage *image) {
UIImage *modifiedImage;
CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
UIGraphicsBeginImageContextWithOptions(image.size, false, [[UIScreen mainScreen] scale]);
[[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:44.0] addClip];
[image drawInRect:rect];
modifiedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return modifiedImage;
};
imageModificationBlock 会在图片解码完成之后调用,此处,参数 image 是解码后的正方形图片。
通过
[[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:44.0] addClip];
设置圆角。(PS:项目中可以直接使用)。
当然不是每次都做圆角的处理,缓存还是要做的。
……
///获取 ASWeakMapEntry 对象
ASWeakMapEntry<UIImage *> *entry = [self.class contentsForkey:contentsKey isCancelled:(asdisplaynode_iscancelled_block_t)isCancelled];
if (entry == nil) { // If nil, we were cancelled.
return nil;
}
_weakCacheEntry = entry; // Retain so that the entry remains in the weak cache
……
<code>ASWeakMapEntry</code>的声明如下:
@interface ASWeakMapEntry<Value> : NSObject
@property (nonatomic, retain, readonly) Value value;
@end
此处就仅仅存放了一个 UIImage 对象。
下面看从缓存获取图片的过程
+ (ASWeakMapEntry *)contentsForkey:(ASImageNodeContentsKey *)key isCancelled:(asdisplaynode_iscancelled_block_t)isCancelled
{
{
ASDN::MutexLocker l(cacheLock);
if (!cache) {
cache = [[ASWeakMap alloc] init];
}
///如果缓存中有,直接返回
ASWeakMapEntry *entry = [cache entryForKey:key];
if (entry != nil) {
// cache hit
return entry;
}
}
// 缓存中没有,直接创建。
UIImage *contents = [self createContentsForkey:key isCancelled:isCancelled];
if (contents == nil) { // If nil, we were cancelled
return nil;
}
{
ASDN::MutexLocker l(cacheLock);
return [cache setObject:contents forKey:key];
}
}
Entry 对象都存在 ASWeakMap 中。
此处缓存中没有的话,直接调用 createContentsForkey 方法去创建。创建过程,无非就是解码当前图片,解码完了调用 imageModificationBlock 。这里之所以使用block 因为,说不定有其他效果什么的。
<code>ASWeakMap</code>的声明如下:
@interface ASWeakMap<__covariant Key : NSObject *, Value> : NSObject
/**
* Read from the cache. The Value object is accessible from the returned ASWeakMapEntry.
*/
- (nullable ASWeakMapEntry<Value> *)entryForKey:(Key)key;
/**
* Put a value into the cache. If an entry with an equal key already exists, then the value is updated on the existing entry.
*/
- (ASWeakMapEntry<Value> *)setObject:(Value)value forKey:(Key)key;
@end
如果有图片圆角影响性能的,可以参考此处做法。ASWeakMap 可以直接从 AsyncDisplayKit 中扒出来使用的,没有任何依赖。。
网友评论