#import "UIImageView+WebImage.h"
#import "NSString+URLEncoding.h"
@implementation UIImageView (WebImage)
#pragma mark - 模糊图渲染
- (void)renderBlurredImageWithUrl:(NSString *)url placeholder:(UIImage *)placeholder completed:(imageDownloadCompletedBlock) completedBlock
{
// 这里必须开启内存缓存
[SDWebImageManager sharedManager].imageCache.shouldCacheImagesInMemory = YES;
// 渲染背景
__weak typeof(self) ws = self;
[ws sd_setImageWithURL:[NSURL URLWithString:url] completed:^(UIImage *webImage, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
// 999 是一个标记
if (ws.tag != 999) {
UIVisualEffectView *visualView = [[UIVisualEffectView alloc] initWithFrame:ws.bounds];
UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
visualView.effect = effect;
NSLog(@"only once");
[ws addSubview:visualView];
ws.tag = 999;
}
ws.alpha =0.6;
ws.image = nil;
ws.image = webImage;
if (completedBlock) {
completedBlock(webImage);
}
}];
}
#pragma mark - 裁剪图片
- (void)yg_setTrimImageWithUrl:(NSString *)url placeholderImage:(UIImage *)placeholder{
__weak typeof(self) ws = self;
[SDWebImageManager sharedManager].imageCache.shouldCacheImagesInMemory = NO;
[self sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:placeholder completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (image) {
UIImage *img=[self yg_trimImageWithImage:image];
ws.image=img;
}else{
ws.image =[self yg_trimImageWithImage:placeholder];
}
}];
}
-(UIImage *)yg_trimImageWithImage:(UIImage *)image{
//imageView的宽高比
CGFloat imageViewWidthHeightRatio =self.frame.size.width/self.frame.size.height;
//屏幕分辨率
// CGFloat imageScale = [[UIScreen mainScreen] scale];
CGFloat imageScale = 1;
CGFloat imageWith = image.size.width*imageScale;
CGFloat imageHeight =image.size.height*imageScale;
//image的宽高比
CGFloat imageWidthHeightRatio =imageWith/imageHeight;
CGImageRef imageRef = nil;
CGRect rect;
// NSLog(@"nimageWith === %fnimageHeight === %fnImageView宽高比 == %fnimageScale == %f",imageWith,imageHeight,imageViewWidthHeightRatio,imageScale);
if (imageWidthHeightRatio>imageViewWidthHeightRatio) {
rect = CGRectMake((imageWith-imageHeight*imageViewWidthHeightRatio)/2, 0, imageHeight*imageViewWidthHeightRatio, imageHeight);
}else if (imageWidthHeightRatio<imageViewWidthHeightRatio) {
rect = CGRectMake(0, (imageHeight-imageWith/imageViewWidthHeightRatio)/2, imageWith, imageWith/imageViewWidthHeightRatio);
}else {
rect = CGRectMake(0, 0, imageWith, imageHeight);
}
imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
UIImage *res = [UIImage imageWithCGImage:imageRef scale:imageScale orientation:UIImageOrientationUp];
/**
一定要,千万要release,否则等着内存泄露吧,稍微高清点的图一张图就是几M内存,很快App就挂了
*/
CGImageRelease(imageRef);
return res;
}
@end
近期评论