iOS开发中我们会经常对图片进行切圆角操作,常见的做法是这样的:
myImgView.layer.cornerRadius = 25;
myImgView.layer.masksToBounds = YES;
其中masksToBounds(CALayer)表示视图的图层上的子图层,如果超出父图层的部分就截取掉;还有clipsToBounds(UIView),是指视图上的子视图,如果超出父视图的部分就截取掉。
在iOS9.0之前这样设置会触发离屏渲染,比较消耗性能。比如当一个页面上有十几头像这样设置了圆角,尤其是tableView中,大量操作会明显的感到页面的轻微卡顿。
GitHub上有不少开源的第三方,其中基本都是用了Core Graphics绘制圆角。其实只要在你的UIImageView的分类中加一个方法即可:
+ (UIImage *)imageWithRoundCorner:(UIImage *)sourceImage cornerRadius:(CGFloat)cornerRadius size:(CGSize)size{
CGFloat scale = [UIScreen mainScreen].scale;
UIGraphicsBeginImageContextWithOptions(size, NO, scale);
CGRect bounds = CGRectMake(0, 0, size.width, size.height);
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:bounds cornerRadius:cornerRadius];
[path addClip];
[sourceImage drawInRect:bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
也可以和SDWebImage相结合:
- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock {
[self sd_cancelCurrentImageLoad];
if (!(options & SDWebImageDelayPlaceholder)) {
dispatch_main_async_safe(^{
self.image = [self _vvr_processImage:placeholder];
});
}
if (url) {
__weak __typeof(self)wself = self;
id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
if (!wself) return;
dispatch_main_sync_safe(^{
if (!wself) return;
if (image && (options & SDWebImageAvoidAutoSetImage) && completedBlock)
{
completedBlock([self _vvr_processImage:image], error, cacheType, url);
return;
}
else if (image) {
wself.image = [self _vvr_processImage:image];
[wself setNeedsLayout];
} else {
if ((options & SDWebImageDelayPlaceholder)) {
wself.image = [self _vvr_processImage:placeholder];
[wself setNeedsLayout];
}
}
if (completedBlock && finished) {
completedBlock(image, error, cacheType, url);
}
});
}];
[self sd_setImageLoadOperation:operation forKey:@"UIImageViewImageLoad"];
} else {
dispatch_main_async_safe(^{
if (completedBlock) {
NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
completedBlock(nil, error, SDImageCacheTypeNone, url);
}
});
}
}
© 著作权归作者所有
文章评论(0)