SDWebImage: 带你制作精美的相册

来源:互联网 发布:阿里云设置端口映射 编辑:程序博客网 时间:2024/04/29 16:24

这里写图片描述


说起 SDWebImage 大家肯定都不陌生,它在GitHub上的星星有16300多个,可见其火爆程度;作为目前最受欢迎的第三方图片下载框架,在app开发中使用率很高,尤其是需要处理大量图片的项目。

这里写图片描述

这个类库提供一个UIImageView类别,支持加载来自网络的远程图片。具有缓存管理、异步下载、同一个URL下载次数控制和优化等特征,跳转SDWebImage下载地址。

在本篇文章中,我将以示例的方式来给大家演示如何使用SDWebImage这个框架,制作一个漂亮的相册,效果图如下:

效果图 1 效果图 2

首先,将下载好的SDWebImage.framework添加到我们的Xcode工程中,在类头文件(.h)中导入头文件:

#import <SDWebImage/UIImageView+WebCache.h>#import <SDWebImage/FLAnimatedImageView+WebCache.h>

在上面的效果图中,大家肯定一眼就看出来这是一个UITableView;没错,对于展示类的页面来讲,UITableView就是最佳的选择,如果你接触iOS开发到一定的阶段,你就会发现UITableView这个控件实在是太强大了。

现在的社会是一个看颜值的社会,好看的界面当然离不开我们去自定义控件;在这个tableView中,我们自定义了UITableViewCell,代码如下:

@implementation YYWebImageExampleCell- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];    self.backgroundColor = [UIColor clearColor];    self.contentView.backgroundColor = [UIColor clearColor];    self.size = CGSizeMake(kScreenWidth, kCellHeight);    self.contentView.size = self.size;    _webImageView = [FLAnimatedImageView new];    _webImageView.size = self.size;    _webImageView.clipsToBounds = YES;    _webImageView.contentMode = UIViewContentModeScaleAspectFill;    _webImageView.backgroundColor = [UIColor whiteColor];    [self.contentView addSubview:_webImageView];    _label = [UILabel new];    _label.size = self.size;    _label.textAlignment= NSTextAlignmentCenter;    _label.text = @"Load fail, tap to reload.";    _label.textColor = [UIColor colorWithWhite:0.7 alpha:1.0];    _label.hidden = YES;    _label.userInteractionEnabled = YES;    [self.contentView addSubview:_label];    CGFloat lineHeight = 4;    _progressLayer = [CAShapeLayer new];    _progressLayer.size = CGSizeMake(_webImageView.width, lineHeight);    UIBezierPath *path = [UIBezierPath bezierPath];    [path moveToPoint:CGPointMake(0, _progressLayer.height / 2)];    [path addLineToPoint:CGPointMake(_webImageView.width, _progressLayer.height / 2)];    _progressLayer.lineWidth = lineHeight;    _progressLayer.path = path.CGPath;    _progressLayer.strokeColor = [UIColor colorWithRed:0 green:0.6 blue:1.0 alpha:0.72].CGColor;    _progressLayer.lineCap = kCALineCapButt;    _progressLayer.strokeStart = 0;    _progressLayer.strokeEnd = 0;    [_webImageView.layer addSublayer:_progressLayer];    return self;}- (void)setImageURL:(NSURL *)url{    _label.hidden = YES;    [CATransaction begin];    [CATransaction setDisableActions:YES];    self.progressLayer.hidden = YES;    self.progressLayer.strokeEnd = 0;    [CATransaction commit];    [_webImageView sd_setImageWithURL:url placeholderImage:nil options:SDWebImageProgressiveDownload progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {        dispatch_async(dispatch_get_main_queue(), ^{            if(receivedSize > 0 && receivedSize > 0){                CGFloat progress = (CGFloat)receivedSize / expectedSize;                progress = progress < 0 ? 0 : progress > 1 ? 1 : progress;                if(_progressLayer.hidden) _progressLayer.hidden = NO;                _progressLayer.strokeEnd = progress;            }        });    } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {        dispatch_async(dispatch_get_main_queue(), ^{            if(image){                _progressLayer.hidden = YES;                CATransition *transition = [CATransition animation];                transition.duration = 0.2;                transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];                transition.type = kCATransitionFade;                [self.layer addAnimation:transition forKey:@"YYWebImageFade"];            }        });    }];}@end

这个自定义的Cell, 主要是由 FLAnimatedImageView(由SDWebImage库所提供), CAShapeLayer,以及UILable所构成,并抛出一个设置图片的接口,该接口会去调用SDWebImage库中的下载图片并缓存接口:

- (void)sd_setImageWithURL:(nullable NSURL *)url          placeholderImage:(nullable UIImage *)placeholder                   options:(SDWebImageOptions)options                  progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock                 completed:(nullable SDExternalCompletionBlock)completedBlock;

自定义好了Cell,接下来就要去创建一个UITableView控件去加载它,代码如下:

#define kCellHeight ceil((kScreenWidth) * 3.0 / 4.0)#ifndef kSystemVersion#define kSystemVersion [[UIDevice currentDevice].systemVersion floatValue]#endif#ifndef kiOS6Later#define kiOS6Later (kSystemVersion >= 6)#endif#ifndef kiOS7Later#define kiOS7Later (kSystemVersion >= 7)#endif#ifndef kiOS8Later#define kiOS8Later (kSystemVersion >= 8)#endif#ifndef kiOS9Later#define kiOS9Later (kSystemVersion >= 9)#endif@implementation YYWebImageExample{    NSArray *_imageLinks;}- (void)viewDidLoad{    [super viewDidLoad];    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;    self.view.backgroundColor = [UIColor whiteColor];    UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:@"Reload" style:UIBarButtonItemStylePlain target:self action:@selector(reload)];    self.navigationItem.rightBarButtonItem = button;    self.view.backgroundColor = [UIColor colorWithWhite:0.217 alpha:1.000];    NSArray *links = @[                       // progressive jpeg                       @"https://s-media-cache-ak0.pinimg.com/1200x/2e/0c/c5/2e0cc5d86e7b7cd42af225c29f21c37f.jpg",                       // animated gif: http://cinemagraphs.com/                       @"http://i.imgur.com/uoBwCLj.gif",                       @"http://i.imgur.com/8KHKhxI.gif",                       @"http://i.imgur.com/WXJaqof.gif",                       // animated gif: https://dribbble.com/markpear                       @"https://d13yacurqjgara.cloudfront.net/users/345826/screenshots/1780193/dots18.gif",                       @"https://d13yacurqjgara.cloudfront.net/users/345826/screenshots/1809343/dots17.1.gif",                       @"https://d13yacurqjgara.cloudfront.net/users/345826/screenshots/1845612/dots22.gif",                       @"https://d13yacurqjgara.cloudfront.net/users/345826/screenshots/1820014/big-hero-6.gif",                       @"https://d13yacurqjgara.cloudfront.net/users/345826/screenshots/1819006/dots11.0.gif",                       @"https://d13yacurqjgara.cloudfront.net/users/345826/screenshots/1799885/dots21.gif",                       // animaged gif: https://dribbble.com/jonadinges                       @"https://d13yacurqjgara.cloudfront.net/users/288987/screenshots/2025999/batman-beyond-the-rain.gif",                       @"https://d13yacurqjgara.cloudfront.net/users/288987/screenshots/1855350/r_nin.gif",                       @"https://d13yacurqjgara.cloudfront.net/users/288987/screenshots/1963497/way-back-home.gif",                       @"https://d13yacurqjgara.cloudfront.net/users/288987/screenshots/1913272/depressed-slurp-cycle.gif",                       // jpg: https://dribbble.com/snootyfox                       @"https://d13yacurqjgara.cloudfront.net/users/26059/screenshots/2047158/beerhenge.jpg",                       @"https://d13yacurqjgara.cloudfront.net/users/26059/screenshots/2016158/avalanche.jpg",                       @"https://d13yacurqjgara.cloudfront.net/users/26059/screenshots/1839353/pilsner.jpg",                       @"https://d13yacurqjgara.cloudfront.net/users/26059/screenshots/1833469/porter.jpg",                       @"https://d13yacurqjgara.cloudfront.net/users/26059/screenshots/1521183/farmers.jpg",                       @"https://d13yacurqjgara.cloudfront.net/users/26059/screenshots/1391053/tents.jpg",                       @"https://d13yacurqjgara.cloudfront.net/users/26059/screenshots/1399501/imperial_beer.jpg",                       @"https://d13yacurqjgara.cloudfront.net/users/26059/screenshots/1488711/fishin.jpg",                       @"https://d13yacurqjgara.cloudfront.net/users/26059/screenshots/1466318/getaway.jpg",                       // animated webp and apng: http://littlesvr.ca/apng/gif_apng_webp.html                       @"http://littlesvr.ca/apng/images/BladeRunner.png",                       @"http://littlesvr.ca/apng/images/Contact.webp",                       ];    _imageLinks = links;    [self.tableView reloadData];    [self scrollViewDidScroll:self.tableView];}- (void)viewDidAppear:(BOOL)animated{    [super viewDidAppear:animated];    if(kiOS7Later){        self.navigationController.navigationBar.barStyle = UIBarStyleBlack;        self.navigationController.navigationBar.tintColor = [UIColor whiteColor];    }    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;}- (void)viewWillDisappear:(BOOL)animated{    [super viewWillDisappear:animated];    if(kiOS7Later){        self.navigationController.navigationBar.barStyle = UIBarStyleDefault;        self.navigationController.navigationBar.tintColor = nil;    }    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;}- (void)reload{    [self.tableView reloadData];}- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath{    return NO;}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{    return _imageLinks.count * 4;}- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{    return kCellHeight;}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    YYWebImageExampleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];    if (!cell) cell = [[YYWebImageExampleCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];    [cell setImageURL:[NSURL URLWithString:_imageLinks[indexPath.row % _imageLinks.count]]];    return cell;}- (void)scrollViewDidScroll:(UIScrollView *)scrollView{    CGFloat viewHeight = scrollView.height + scrollView.contentInset.top;   for(YYWebImageExampleCell *cell in [self.tableView visibleCells]){        CGFloat y = cell.centerY - scrollView.contentOffset.y;        CGFloat p = y - viewHeight / 2;        CGFloat scale= cos(p / viewHeight * 0.8) * 0.95;        if(kiOS8Later){            [UIView animateWithDuration:0.15 delay:0 options:UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionBeginFromCurrentState animations:^{                cell.webImageView.transform = CGAffineTransformMakeScale(scale, scale);            } completion:^(BOOL finished) {            }];        }else{            cell.webImageView.transform = CGAffineTransformMakeScale(scale, scale);        }    }}@end

这里UITableView的功能比较简单,就不多做介绍了。

总结:

SDWebImage是一个功能很强大的图片加载库,我上面所演示的只是最基础的下载与缓存功能,适用于这种相册功能;如果你的App功能对性能优化或者内存管理的要求比较高,它还有独立的异步图像下载,异步图像缓存可供使用;总之,SDWebImage的出现对我们开发者来说,是一个不错的选择。

参考文章:
https://github.com/rs/SDWebImage
https://github.com/ibireme/YYKit


好了。祝大家生活愉快。多多收获友谊和爱情。如果想获取更多的讯息,请扫描下方二维码关注我的微信公众号:

这里写图片描述

1 0
原创粉丝点击