本文的category是根据VIPhotoView来做参考,在此基础上添加个加载网络图片。
此category主要功能是与图片进行交互,双击放大图片,捏合等操作。
感谢
/** 显示的图片,提供给外界调用,用于保存图片 */ @property (strong, nonatomic) UIImageView *imageView; /** 加载网络图片 */ + (instancetype)photoViewWithFrame:(CGRect)frame atImageUrlString:(NSString *)urlString; - (instancetype)initWithFrame:(CGRect) frame atImageUrlString:(NSString *)urlString; /** 加载本地图片 */ + (instancetype)photoViewWithFrame:(CGRect)frame atImageName:(NSString *)imageName; - (instancetype)initWithFrame:(CGRect)frame atImageName:(NSString *)imageName;
内部实现图片缓存,默认缓存到NSCachesDirectory
- (void)setupImageOfURLString:(NSString *)urlString { /** 取得沙盒路径 */ NSString *cachesDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; /** 取得图片名 */ NSString *imageName = [[urlString lastPathComponent] stringByDeletingPathExtension]; /** 取得图片扩展名 */ NSString *imageExtension = [urlString pathExtension]; /** 先从沙盒中取出图片 */ UIImage *image = [UIImage loadImage:imageName ofType:imageExtension inDirectory:cachesDirectory]; /** 当图片不存在 */ if (!image) { NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]]; image = [UIImage imageWithData:data]; /** 下载图片后存储到沙盒中 */ [image saveImage:image atFileName:imageName atImageType:imageExtension atDirectory:cachesDirectory]; } self.imageView.image = image; }
使用PhotoView
- (void)viewDidLoad { [super viewDidLoad]; NSString *urlString = @"http://ww4.sinaimg.cn/large/7a8aed7bgw1ev1yplngebj20hs0qogq0.jpg"; /** 加载网络图片 */ XQPhotoView *photoView = [XQPhotoView photoViewWithFrame:self.view.bounds atImageUrlString:urlString]; /** 加载本地图片 */ // XQPhotoView *photoView = [XQPhotoView photoViewWithFrame:self.view.bounds atImageName:@"7a8aed7bgw1euqcfwjbkdj20hs0qo40w.jpg"]; [self.view addSubview:photoView]; }
本文的缓存考虑的不足,但是用SDWebImage来做缓存的话,对其具有依赖性,所以就没有使用SDWebImage
如果有更好的缓存方法,请与我联系,指导我一下,谢谢~
demo链接:https://github.com/XQBoy/PhotoView
demo演示: