工作三年了叉趣,都沒寫過博客泞边,沒想到第一篇居然在簡書上寫的。
最近工作不好找啊疗杉,寫點博客聊以自慰吧阵谚。不吐槽了,開始上正題吧烟具。
我們經常會遇到頭像圓角問題梢什,當然如果一個界面里就一個圓角的imageView,感覺也沒必要優(yōu)化朝聋。
簡單粗暴代碼如下:
imageView.layer.cornerRadius = CGRectGetWidth(imageView.bounds)/2;
imageView.layer.masksToBounds = YES;
但是當在一個tableView的每一個Cell中的imageView都要設置圓角的話绳矩,麻煩就來了。就會導致離屏渲染玖翅,讓CPU處理它不擅長而GPU擅長的切圖工作翼馆,讓GPU等著渲染。一幀下來金度,CPU還沒處理完应媚,GPU只能不渲染了,這就引起了掉幀猜极≈薪滑動卡頓是必須的。
當然了跟伏,用GPU去切圖就好了丢胚,所以最好的辦法就是對image進行處理,切圓角受扳。我用了一個image的category添加一個方法處理圖片圓角
@interface UIImage (WebRadius)
- (UIImage*)imageByRoundCornerRadius;
@end
@implementation UIImage (WebRadius)
- (UIImage*)imageByRoundCornerRadius{
UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextScaleCTM(context, 1, -1);
CGContextTranslateCTM(context, 0, -self.size.height);
CGFloat minSize = MIN(self.size.width, self.size.height);
CGRect rect = CGRectMake((self.size.width-minSize)/2, (self.size.height-minSize)/2, minSize, minSize);
UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:minSize/2];
[path closePath];
CGContextSaveGState(context);
[path addClip];
CGContextDrawImage(context, rect, self.CGImage);
CGContextRestoreGState(context);
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
@end
圖片只需要調用這個方法就可以進行image圓角處理携龟。處理是在GPU中進行。(靈感來源于YYKit)
那么對于網絡加載的圖片該怎么處理勘高?
我們很多人會使用SDWebImage進行網絡請求圖片峡蟋,難道每次獲取圖片都要進行圖片圓角化處理坟桅,然后顯示嗎?如果tableview一直滑動蕊蝗,那不是一直在圓角化處理嗎仅乓?于是我想在SDWebImage從網絡下載中對圖片圓角化處理一下,然后保存在memory和disk中蓬戚,再次從緩存中獲取圖片就不用圓角化處理了夸楣。SDWebImage在從網絡下載圖片成功后一般都會走SDImageCache的
storeImage:imageData:forKey:toDisk:completion:
方法進行保存。于是我使用了SDImageCache的category替換了storeImage:imageData:forKey:toDisk:completion:方法
代碼如下:
@interface SDImageCache (WebRadius)
@property (nonatomic,retain)NSNumber * isCornerRadius;
@end
@implementation SDImageCache (WebRadius)
+ (void)load{
Method originalMethod = class_getInstanceMethod(self, @selector(storeImage:imageData:forKey:toDisk:completion:));
Method myMethod = class_getInstanceMethod(self, @selector(lh_storeImage:imageData:forKey:toDisk:completion:));
method_exchangeImplementations(originalMethod, myMethod);
}
static const char cornerRadiusKey = '\0';
- (void)setIsCornerRadius:(NSNumber *)isCornerRadius{
[self willChangeValueForKey:@"isCornerRadius"];
objc_setAssociatedObject(self, &cornerRadiusKey, isCornerRadius, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[self didChangeValueForKey:@"isCornerRadius"];
}
- (NSNumber*)isCornerRadius{
return objc_getAssociatedObject(self, &cornerRadiusKey);
}
- (void)lh_storeImage:(nullable UIImage *)image
imageData:(nullable NSData *)imageData
forKey:(nullable NSString *)key
toDisk:(BOOL)toDisk
completion:(nullable SDWebImageNoParamsBlock)completionBlock
{
if (!image || !key) {
if (completionBlock) {
completionBlock();
}
return;
}
if ([self.isCornerRadius boolValue]) {
image = [image imageByRoundCornerRadius];
NSString * imageType = [self typeForImageData:imageData];
if ([imageType isEqualToString:@"image/jpeg"]) {
imageData = UIImageJPEGRepresentation(image, 1.0);
}
else if ([imageType isEqualToString:@"image/png"]){
imageData = UIImagePNGRepresentation(image);
}
}
Ivar memCachevar = class_getInstanceVariable([self class], [@"memCache" UTF8String]);
if (memCachevar == nil) {
memCachevar = class_getInstanceVariable([self class], [[NSString stringWithFormat:@"_%@",@"memCache"] UTF8String]);
}
NSCache * memCache = object_getIvar(self, memCachevar);
Ivar ioQueuevar = class_getInstanceVariable([self class], [@"ioQueue" UTF8String]);
if (ioQueuevar == nil) {
ioQueuevar = class_getInstanceVariable([self class], [[NSString stringWithFormat:@"_%@",@"ioQueue"] UTF8String]);
}
dispatch_queue_t ioQueue = object_getIvar(self, ioQueuevar);
if (self.config.shouldCacheImagesInMemory) {
NSUInteger cost = image.size.height * image.size.width * image.scale * image.scale;
[memCache setObject:image forKey:key cost:cost];
}
if (toDisk) {
dispatch_async(ioQueue, ^{
@autoreleasepool {
NSData *data = imageData;
if (!data && image) {
SDImageFormat imageFormatFromData = [NSData sd_imageFormatForImageData:data];
data = [image sd_imageDataAsFormat:imageFormatFromData];
}
[self storeImageDataToDisk:data forKey:key];
}
if (completionBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock();
});
}
});
}
else {
if (completionBlock) {
completionBlock();
}
}
}
- (NSString *)typeForImageData:(NSData *)data {
uint8_t c;
[data getBytes:&c length:1];
switch (c) {
case 0xFF:
return @"image/jpeg";
case 0x89:
return @"image/png";
case 0x47:
return @"image/gif";
case 0x49:
case 0x4D:
return @"image/tiff";
}
return nil;
}
其中isCornerRadius是是否圓角的判斷子漩。這樣就可以在不修改SDWebImage源碼的情況下進行圖片圓角操作了裕偿。不過主程序就得這樣寫
[SDImageCache sharedImageCache].isCornerRadius = [NSNumber numberWithBool:YES];
UIImageView * imageView = [[UIImageView alloc] init];
imageView.backgroundColor = [UIColor clearColor];
NSString * urlString = @"http://www.cdhdky.com/images/ttt.jpg";
UIImage * image = [[SDImageCache sharedImageCache] imageFromCacheForKey:urlString];
if (image) {
imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height);
imageView.center = self.view.center;
imageView.image = image;
}
else{
__weak __typeof(self) weakSelf = self;
[[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:urlString] options:SDWebImageRetryFailed progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height);
imageView.center = weakSelf.view.center;
imageView.image = [[SDImageCache sharedImageCache]imageFromCacheForKey:imageURL.absoluteString];
}];
}
[self.view addSubview:imageView];
本人有點懶,如果有什么不懂的請留言痛单。這個category有點缺陷需要繼續(xù)完善嘿棘。從今天起,開始分享我的知識旭绒,雖然我很笨鸟妙。
完整demo在github中。