mirror of
https://github.com/DmcSDK/cordova-plugin-mediaPicker
synced 2026-05-03 00:00:04 +08:00
ios preview
This commit is contained in:
@@ -4,10 +4,10 @@
|
||||
|
||||
|
||||
@interface CollectionViewCell : UICollectionViewCell
|
||||
@property(nonatomic ,strong)UIImageView *imgView;
|
||||
@property(nonatomic ,strong)UIImageView *whiteView;
|
||||
@property(nonatomic ,strong)UIImageView *checkView;
|
||||
@property(nonatomic ,strong)UILabel *labelL;
|
||||
@property(nonatomic ,strong)UILabel *labelR;
|
||||
@property(nonatomic ,strong)UILabel *labeGIF;
|
||||
@end
|
||||
@property(nonatomic ,strong)UIImageView *imgView;
|
||||
@property(nonatomic ,strong)UIImageView *whiteView;
|
||||
@property(nonatomic ,strong)UIImageView *checkView;
|
||||
@property(nonatomic ,strong)UILabel *labelL;
|
||||
@property(nonatomic ,strong)UILabel *labelR;
|
||||
@property(nonatomic ,strong)UILabel *labeGIF;
|
||||
@end
|
||||
|
||||
@@ -4,58 +4,56 @@
|
||||
|
||||
@implementation CollectionViewCell
|
||||
- (id)initWithFrame:(CGRect)frame
|
||||
{
|
||||
self = [super initWithFrame:frame];
|
||||
if (self) {
|
||||
CGFloat width=CGRectGetWidth(self.frame);
|
||||
|
||||
self.imgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, width, width)];
|
||||
self.imgView.contentMode=UIViewContentModeScaleAspectFill;
|
||||
self.imgView.clipsToBounds=YES;
|
||||
|
||||
CGFloat checkWidth=width/5;
|
||||
self.checkView=[[UIImageView alloc]initWithFrame:CGRectMake(width-checkWidth-5, 5, checkWidth, checkWidth)];
|
||||
self.whiteView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, width, width)];
|
||||
|
||||
|
||||
CGFloat labelH=width/6;
|
||||
self.labelL = [[UILabel alloc]initWithFrame:CGRectMake(0, width-labelH, width/2, labelH)];
|
||||
self.labelL.textColor=[UIColor whiteColor];
|
||||
self.labelL.font=[UIFont systemFontOfSize:13.0];
|
||||
self.labelL.backgroundColor= [[UIColor blackColor] colorWithAlphaComponent:0.3f];
|
||||
|
||||
|
||||
self.labelR = [[UILabel alloc]initWithFrame:CGRectMake(width/2, width-labelH, width/2, labelH)];
|
||||
self.labelR.textColor=[UIColor whiteColor];
|
||||
self.labelR.font=[UIFont systemFontOfSize:13.0];
|
||||
self.labelR.textAlignment=NSTextAlignmentRight;
|
||||
self.labelR.backgroundColor= [[UIColor blackColor] colorWithAlphaComponent:0.3f];
|
||||
|
||||
|
||||
self.labeGIF = [[UILabel alloc] initWithFrame:CGRectMake(width-width/5-5, width-labelH-2, width/5, labelH-5)];
|
||||
self.labeGIF.backgroundColor = [UIColor clearColor];
|
||||
self.labeGIF.textColor=[UIColor whiteColor];
|
||||
self.labeGIF.text=@"\tGIF\t";
|
||||
self.labeGIF.layer.cornerRadius =4;
|
||||
self.labeGIF.layer.masksToBounds =YES;
|
||||
self.labeGIF.textAlignment= NSTextAlignmentCenter;
|
||||
self.labeGIF.baselineAdjustment= UIBaselineAdjustmentAlignCenters;
|
||||
self.labeGIF.font=[UIFont systemFontOfSize:13.0];
|
||||
self.labeGIF.adjustsFontSizeToFitWidth = YES;
|
||||
self.labeGIF.textAlignment=NSTextAlignmentRight;
|
||||
self.labeGIF.backgroundColor= [[UIColor blackColor] colorWithAlphaComponent:0.4f];
|
||||
|
||||
|
||||
|
||||
|
||||
[self addSubview:self.imgView];
|
||||
[self addSubview:self.whiteView];
|
||||
[self addSubview:self.checkView];
|
||||
[self addSubview:self.labelL];
|
||||
[self addSubview:self.labelR];
|
||||
[self addSubview:self.labeGIF];
|
||||
|
||||
{
|
||||
self = [super initWithFrame:frame];
|
||||
if (self) {
|
||||
CGFloat width=CGRectGetWidth(self.frame);
|
||||
|
||||
self.imgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, width, width)];
|
||||
self.imgView.contentMode=UIViewContentModeScaleAspectFill;
|
||||
self.imgView.clipsToBounds=YES;
|
||||
|
||||
CGFloat checkWidth=width/5;
|
||||
self.checkView=[[UIImageView alloc]initWithFrame:CGRectMake(width-checkWidth-5, 5, checkWidth, checkWidth)];
|
||||
self.whiteView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, width, width)];
|
||||
|
||||
|
||||
CGFloat labelH=width/6;
|
||||
self.labelL = [[UILabel alloc]initWithFrame:CGRectMake(0, width-labelH, width/2, labelH)];
|
||||
self.labelL.textColor=[UIColor whiteColor];
|
||||
self.labelL.font=[UIFont systemFontOfSize:13.0];
|
||||
self.labelL.backgroundColor= [[UIColor blackColor] colorWithAlphaComponent:0.3f];
|
||||
|
||||
|
||||
self.labelR = [[UILabel alloc]initWithFrame:CGRectMake(width/2, width-labelH, width/2, labelH)];
|
||||
self.labelR.textColor=[UIColor whiteColor];
|
||||
self.labelR.font=[UIFont systemFontOfSize:13.0];
|
||||
self.labelR.textAlignment=NSTextAlignmentRight;
|
||||
self.labelR.backgroundColor= [[UIColor blackColor] colorWithAlphaComponent:0.3f];
|
||||
|
||||
|
||||
self.labeGIF = [[UILabel alloc] initWithFrame:CGRectMake(width-width/5-5, width-labelH-2, width/5, labelH-5)];
|
||||
self.labeGIF.backgroundColor = [UIColor clearColor];
|
||||
self.labeGIF.textColor=[UIColor whiteColor];
|
||||
self.labeGIF.text=@"\tGIF\t";
|
||||
self.labeGIF.layer.cornerRadius =4;
|
||||
self.labeGIF.layer.masksToBounds =YES;
|
||||
self.labeGIF.textAlignment= NSTextAlignmentCenter;
|
||||
self.labeGIF.baselineAdjustment= UIBaselineAdjustmentAlignCenters;
|
||||
self.labeGIF.font=[UIFont systemFontOfSize:13.0];
|
||||
self.labeGIF.adjustsFontSizeToFitWidth = YES;
|
||||
//self.labeGIF.textAlignment=NSTextAlignmentRight;
|
||||
self.labeGIF.backgroundColor= [[UIColor blackColor] colorWithAlphaComponent:0.4f];
|
||||
|
||||
|
||||
[self addSubview:self.imgView];
|
||||
[self addSubview:self.whiteView];
|
||||
[self addSubview:self.checkView];
|
||||
[self addSubview:self.labelL];
|
||||
[self addSubview:self.labelR];
|
||||
[self addSubview:self.labeGIF];
|
||||
|
||||
}
|
||||
return self;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
@end
|
||||
@end
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
#import <Photos/Photos.h>
|
||||
#import "PreviewViewController.h"
|
||||
@protocol DmcPickerDelegate<NSObject>
|
||||
-(void) resultPicker:(NSMutableArray*) selectArray;
|
||||
@end
|
||||
|
||||
@interface DmcPickerViewController : UIViewController <UICollectionViewDataSource,UICollectionViewDelegate>{
|
||||
@interface DmcPickerViewController : UIViewController <UICollectionViewDataSource,UICollectionViewDelegate,DmcPreviewDelegate>{
|
||||
NSMutableArray *_cellArray; //collectionView数据
|
||||
PHFetchResult * fetchResult;
|
||||
NSMutableArray *selectArray;
|
||||
|
||||
@@ -2,15 +2,21 @@
|
||||
|
||||
#import "DmcPickerViewController.h"
|
||||
#import "CollectionViewCell.h"
|
||||
#import "PreviewViewController.h"
|
||||
#import <Photos/Photos.h>
|
||||
#define fDeviceWidth ([UIScreen mainScreen].bounds.size.width) //设备高度的宏
|
||||
#define fDeviceHeight ([UIScreen mainScreen].bounds.size.height)
|
||||
@interface DmcPickerViewController ()
|
||||
@interface DmcPickerViewController (){
|
||||
UIBarButtonItem *preview;
|
||||
int litemCount;
|
||||
UICollectionViewFlowLayout *flowLayout ;
|
||||
}
|
||||
|
||||
@property (strong, nonatomic) PHImageManager *manager;
|
||||
@end
|
||||
|
||||
@implementation DmcPickerViewController
|
||||
|
||||
|
||||
- (void)viewDidLoad {
|
||||
//init config
|
||||
self.maxSelectCount=self.maxSelectCount>0?self.maxSelectCount:15;
|
||||
@@ -20,59 +26,67 @@
|
||||
[super viewDidLoad];
|
||||
[self initView];
|
||||
[self requestPermission];
|
||||
|
||||
|
||||
}
|
||||
|
||||
-(void)initView{
|
||||
|
||||
[[self view]setBackgroundColor:[UIColor greenColor]];
|
||||
-(void)initView{
|
||||
UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Done",nil) style:UIBarButtonItemStylePlain target:self action:@selector(done)];
|
||||
UIBarButtonItem *leftButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Cancel",nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancel)];
|
||||
self.navigationItem.rightBarButtonItem = rightButtonItem;
|
||||
[self setDoneBtnStatus];
|
||||
self.navigationItem.leftBarButtonItem=leftButtonItem;
|
||||
self.navigationItem.title=NSLocalizedString(@"all",nil);
|
||||
|
||||
self.navigationItem.leftBarButtonItem=leftButtonItem;
|
||||
self.navigationItem.title=NSLocalizedString(@"All",nil);
|
||||
|
||||
//bottom bar
|
||||
[self.navigationController setToolbarHidden:NO animated:YES];
|
||||
preview = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Preview",nil) style:UIBarButtonItemStylePlain target:self action:@selector(preview)];
|
||||
[self setToolbarItems:@[preview] animated:YES];
|
||||
[self setBtnStatus];
|
||||
[self.view addSubview:self.collectionView];
|
||||
}
|
||||
|
||||
|
||||
-(void) preview{
|
||||
PreviewViewController * dmc=[[PreviewViewController alloc] init];
|
||||
dmc._delegate=self;
|
||||
dmc.preArray=selectArray;
|
||||
[self.navigationController pushViewController:dmc animated:YES]; // 调用pushViewController
|
||||
}
|
||||
|
||||
-(void) done{
|
||||
[self._delegate resultPicker:selectArray];
|
||||
[self dismissViewControllerAnimated:YES completion:nil];
|
||||
}
|
||||
|
||||
|
||||
-(void) cancel{
|
||||
[self._delegate resultPicker:selectArray];
|
||||
[self dismissViewControllerAnimated:YES completion:nil];
|
||||
}
|
||||
|
||||
|
||||
-(void)requestPermission{
|
||||
//监测权限
|
||||
if ([PHPhotoLibrary authorizationStatus] != PHAuthorizationStatusAuthorized) {
|
||||
if ([PHPhotoLibrary authorizationStatus] != PHAuthorizationStatusAuthorized) {
|
||||
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
|
||||
if ([PHPhotoLibrary authorizationStatus] != PHAuthorizationStatusAuthorized) {
|
||||
UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Unable to access album",nil) message:NSLocalizedString(@"Please allow to access your album",nil) preferredStyle:UIAlertControllerStyleAlert];
|
||||
[alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel",nil) style:UIAlertActionStyleDefault handler:nil]];
|
||||
[alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Setting",nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
|
||||
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
|
||||
}]];
|
||||
[self presentViewController:alert animated:YES completion:nil];
|
||||
}else {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self getAlassetData];
|
||||
});
|
||||
}
|
||||
if ([PHPhotoLibrary authorizationStatus] != PHAuthorizationStatusAuthorized) {
|
||||
UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Unable to access album",nil) message:NSLocalizedString(@"Please allow to access your album",nil) preferredStyle:UIAlertControllerStyleAlert];
|
||||
[alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel",nil) style:UIAlertActionStyleDefault handler:nil]];
|
||||
[alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Setting",nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
|
||||
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
|
||||
}]];
|
||||
[self presentViewController:alert animated:YES completion:nil];
|
||||
}else {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self getAlassetData];
|
||||
});
|
||||
}
|
||||
}];
|
||||
}else {
|
||||
[self getAlassetData];
|
||||
}
|
||||
}else {
|
||||
[self getAlassetData];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
-(void) getAlassetData{
|
||||
|
||||
|
||||
selectArray=[[NSMutableArray alloc] init];
|
||||
|
||||
|
||||
// 获取所有资源的集合,并按资源的创建时间排序
|
||||
PHFetchOptions *options = [[PHFetchOptions alloc] init];
|
||||
options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
|
||||
@@ -87,25 +101,48 @@
|
||||
|
||||
[_collectionView reloadData];
|
||||
}
|
||||
|
||||
|
||||
// TO DO
|
||||
//- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
|
||||
//
|
||||
// [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
|
||||
// [coordinator animateAlongsideTransition:^(id _Nonnull context) {
|
||||
// [_collectionView.collectionViewLayout invalidateLayout];
|
||||
// [UIView performWithoutAnimation:^{
|
||||
// CGFloat w= [UIScreen mainScreen].bounds.size.width;
|
||||
// CGFloat h= [UIScreen mainScreen].bounds.size.height;
|
||||
// _collectionView.frame=CGRectMake(0, 0,w, h);
|
||||
//
|
||||
// flowLayout.itemSize =CGSizeMake((w-(litemCount-1))/litemCount, (w-(litemCount-1))/litemCount);
|
||||
//
|
||||
// [_collectionView setCollectionViewLayout:flowLayout];
|
||||
//
|
||||
// [_collectionView layoutIfNeeded];
|
||||
// }];
|
||||
// [UIView performWithoutAnimation:^{
|
||||
//
|
||||
// [_collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:0 inSection:0]]];
|
||||
// }];
|
||||
// } completion:^(id _Nonnull context) {
|
||||
//
|
||||
// }];
|
||||
//}
|
||||
|
||||
#pragma mark - 创建collectionView并设置代理
|
||||
- (UICollectionView *)collectionView
|
||||
{
|
||||
if (_collectionView == nil) {
|
||||
|
||||
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
|
||||
flowLayout = [[UICollectionViewFlowLayout alloc] init];
|
||||
|
||||
|
||||
|
||||
_collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, fDeviceWidth, fDeviceHeight) collectionViewLayout:flowLayout];
|
||||
|
||||
int count=3;
|
||||
litemCount=3;
|
||||
if([[UIDevice currentDevice].model isEqualToString:@"iPad"]){
|
||||
count=8;
|
||||
litemCount=8;
|
||||
}
|
||||
//定义每个UICollectionView 的大小
|
||||
flowLayout.itemSize = CGSizeMake((fDeviceWidth-2)/count, (fDeviceWidth-2)/count);
|
||||
flowLayout.itemSize = CGSizeMake((fDeviceWidth-(litemCount-1))/litemCount, (fDeviceWidth-(litemCount-1))/litemCount);
|
||||
//定义每个UICollectionView 横向的间距
|
||||
flowLayout.minimumLineSpacing = 1;
|
||||
//定义每个UICollectionView 纵向的间距
|
||||
@@ -129,66 +166,66 @@
|
||||
}
|
||||
return _collectionView;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
#pragma mark - UICollectionView delegate dataSource
|
||||
#pragma mark 定义展示的UICollectionViewCell的个数
|
||||
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
|
||||
{
|
||||
return fetchResult.count;
|
||||
}
|
||||
|
||||
#pragma mark 定义展示的Section的个数
|
||||
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
#pragma mark 每个UICollectionView展示的内容
|
||||
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
|
||||
{
|
||||
static NSString *identify = @"cell";
|
||||
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
|
||||
[cell sizeToFit];
|
||||
PHAsset *asset=fetchResult[indexPath.item];
|
||||
[_manager requestImageForAsset:asset
|
||||
targetSize:CGSizeMake(200 , 200)
|
||||
contentMode:PHImageContentModeAspectFill
|
||||
options:nil
|
||||
resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
|
||||
cell.imgView.image = result;
|
||||
}];
|
||||
NSInteger i=[self isSelect:asset];
|
||||
if(asset.mediaType==PHAssetMediaTypeVideo){
|
||||
cell.labelL.hidden=NO;
|
||||
cell.labelR.hidden=NO;
|
||||
cell.labeGIF.hidden=YES;
|
||||
|
||||
NSString *dtime=[NSString stringWithFormat:@"%.0f",asset.duration];
|
||||
cell.labelL.text=[@"\t"stringByAppendingString:NSLocalizedString(@"Video",nil)];
|
||||
cell.labelR.text=[[self getNewTimeFromDurationSecond:dtime.integerValue]stringByAppendingString:@"\t"];
|
||||
}else{
|
||||
NSString *fileName =[asset valueForKey:@"filename"];
|
||||
NSString * fileExtension = [fileName pathExtension];
|
||||
cell.labeGIF.hidden=[@"GIF" caseInsensitiveCompare:fileExtension]?YES:NO;
|
||||
cell.labelL.hidden=YES;
|
||||
cell.labelR.hidden=YES;
|
||||
{
|
||||
return fetchResult.count;
|
||||
}
|
||||
|
||||
if(i<0){
|
||||
[self hidenSelectView:cell];
|
||||
}else{
|
||||
[self showSelectView:cell];
|
||||
#pragma mark 定义展示的Section的个数
|
||||
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
return cell;
|
||||
}
|
||||
|
||||
|
||||
//UICollectionView被选中时调用的方法
|
||||
|
||||
#pragma mark 每个UICollectionView展示的内容
|
||||
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
|
||||
{
|
||||
static NSString *identify = @"cell";
|
||||
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
|
||||
[cell sizeToFit];
|
||||
PHAsset *asset=fetchResult[indexPath.item];
|
||||
[_manager requestImageForAsset:asset
|
||||
targetSize:CGSizeMake(200 , 200)
|
||||
contentMode:PHImageContentModeAspectFill
|
||||
options:nil
|
||||
resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
|
||||
cell.imgView.image = result;
|
||||
}];
|
||||
NSInteger i=[self isSelect:asset];
|
||||
if(asset.mediaType==PHAssetMediaTypeVideo){
|
||||
cell.labelL.hidden=NO;
|
||||
cell.labelR.hidden=NO;
|
||||
cell.labeGIF.hidden=YES;
|
||||
|
||||
NSString *dtime=[NSString stringWithFormat:@"%.0f",asset.duration];
|
||||
cell.labelL.text=[@"\t"stringByAppendingString:NSLocalizedString(@"Video",nil)];
|
||||
cell.labelR.text=[[self getNewTimeFromDurationSecond:dtime.integerValue]stringByAppendingString:@"\t"];
|
||||
}else{
|
||||
NSString *fileName =[asset valueForKey:@"filename"];
|
||||
NSString * fileExtension = [fileName pathExtension];
|
||||
cell.labeGIF.hidden=[@"GIF" caseInsensitiveCompare:fileExtension]?YES:NO;
|
||||
cell.labelL.hidden=YES;
|
||||
cell.labelR.hidden=YES;
|
||||
}
|
||||
|
||||
if(i<0){
|
||||
[self hidenSelectView:cell];
|
||||
}else{
|
||||
[self showSelectView:cell];
|
||||
}
|
||||
return cell;
|
||||
}
|
||||
|
||||
|
||||
//UICollectionView被选中时调用的方法
|
||||
-( void )collectionView:( UICollectionView *)collectionView didSelectItemAtIndexPath:( NSIndexPath *)indexPath{
|
||||
|
||||
|
||||
PHAsset * asset=fetchResult[indexPath.row];
|
||||
NSInteger i=[self isSelect:asset];
|
||||
CollectionViewCell *cell = (CollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
|
||||
@@ -204,31 +241,46 @@
|
||||
}
|
||||
}
|
||||
|
||||
[self setDoneBtnStatus];
|
||||
[self setBtnStatus];
|
||||
}
|
||||
|
||||
-(void)setDoneBtnStatus{
|
||||
|
||||
-(void)setBtnStatus{
|
||||
if([selectArray count]>0){
|
||||
self.navigationItem.rightBarButtonItem.enabled= YES;
|
||||
preview.enabled= YES;
|
||||
preview.title= [NSLocalizedString(@"Preview",nil)stringByAppendingString:[NSString stringWithFormat:@"(%lu)",(unsigned long)[selectArray count]]];
|
||||
}else{
|
||||
self.navigationItem.rightBarButtonItem.enabled= NO;
|
||||
preview.title= NSLocalizedString(@"Preview",nil);
|
||||
preview.enabled= NO;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
-(void)showSelectView:( CollectionViewCell *)cell{
|
||||
cell.checkView.hidden=NO;
|
||||
cell.whiteView.hidden=NO;
|
||||
cell.whiteView.backgroundColor = [UIColor colorWithWhite:1 alpha:0.5];
|
||||
cell.checkView.image=[UIImage imageNamed:@"dmcPicker.bundle/select80.png"];
|
||||
}
|
||||
|
||||
|
||||
-(void)hidenSelectView:( CollectionViewCell *)cell{
|
||||
cell.checkView.hidden=YES;
|
||||
cell.whiteView.hidden=YES;
|
||||
}
|
||||
|
||||
-(void) previewResultPicker:(NSMutableArray*) srray
|
||||
{
|
||||
selectArray=srray;
|
||||
[self setBtnStatus];
|
||||
[_collectionView reloadData];
|
||||
}
|
||||
|
||||
|
||||
|
||||
-(void) previewDonePicker:(NSMutableArray*) srray
|
||||
{
|
||||
[self._delegate resultPicker:srray];
|
||||
[self dismissViewControllerAnimated:YES completion:nil];
|
||||
}
|
||||
|
||||
-(NSInteger)isSelect:(PHAsset *)asset
|
||||
{
|
||||
int is=-1;
|
||||
@@ -243,11 +295,11 @@
|
||||
}
|
||||
return is;
|
||||
}
|
||||
|
||||
|
||||
- (void)didReceiveMemoryWarning {
|
||||
[super didReceiveMemoryWarning];
|
||||
}
|
||||
|
||||
|
||||
-(void)alertMax{
|
||||
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@""
|
||||
message:NSLocalizedString(@"maxSelectAlert",nil)
|
||||
@@ -257,7 +309,7 @@
|
||||
|
||||
[self presentViewController:alertController animated:YES completion:nil];
|
||||
}
|
||||
|
||||
|
||||
- (NSString *)getNewTimeFromDurationSecond:(NSInteger)duration {
|
||||
NSString *newTime;
|
||||
if (duration < 10) {
|
||||
@@ -275,4 +327,6 @@
|
||||
}
|
||||
return newTime;
|
||||
}
|
||||
@end
|
||||
|
||||
|
||||
@end
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
//
|
||||
// FLAnimatedImage.h
|
||||
// Flipboard
|
||||
//
|
||||
// Created by Raphael Schaad on 7/8/13.
|
||||
// Copyright (c) 2013-2015 Flipboard. All rights reserved.
|
||||
//
|
||||
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
// Allow user classes conveniently just importing one header.
|
||||
#import "FLAnimatedImageView.h"
|
||||
|
||||
|
||||
#ifndef NS_DESIGNATED_INITIALIZER
|
||||
#if __has_attribute(objc_designated_initializer)
|
||||
#define NS_DESIGNATED_INITIALIZER __attribute((objc_designated_initializer))
|
||||
#else
|
||||
#define NS_DESIGNATED_INITIALIZER
|
||||
#endif
|
||||
#endif
|
||||
|
||||
extern const NSTimeInterval kFLAnimatedImageDelayTimeIntervalMinimum;
|
||||
|
||||
//
|
||||
// An `FLAnimatedImage`'s job is to deliver frames in a highly performant way and works in conjunction with `FLAnimatedImageView`.
|
||||
// It subclasses `NSObject` and not `UIImage` because it's only an "image" in the sense that a sea lion is a lion.
|
||||
// It tries to intelligently choose the frame cache size depending on the image and memory situation with the goal to lower CPU usage for smaller ones, lower memory usage for larger ones and always deliver frames for high performant play-back.
|
||||
// Note: `posterImage`, `size`, `loopCount`, `delayTimes` and `frameCount` don't change after successful initialization.
|
||||
//
|
||||
@interface FLAnimatedImage : NSObject
|
||||
|
||||
@property (nonatomic, strong, readonly) UIImage *posterImage; // Guaranteed to be loaded; usually equivalent to `-imageLazilyCachedAtIndex:0`
|
||||
@property (nonatomic, assign, readonly) CGSize size; // The `.posterImage`'s `.size`
|
||||
|
||||
@property (nonatomic, assign, readonly) NSUInteger loopCount; // 0 means repeating the animation indefinitely
|
||||
@property (nonatomic, strong, readonly) NSDictionary *delayTimesForIndexes; // Of type `NSTimeInterval` boxed in `NSNumber`s
|
||||
@property (nonatomic, assign, readonly) NSUInteger frameCount; // Number of valid frames; equal to `[.delayTimes count]`
|
||||
|
||||
@property (nonatomic, assign, readonly) NSUInteger frameCacheSizeCurrent; // Current size of intelligently chosen buffer window; can range in the interval [1..frameCount]
|
||||
@property (nonatomic, assign) NSUInteger frameCacheSizeMax; // Allow to cap the cache size; 0 means no specific limit (default)
|
||||
|
||||
// Intended to be called from main thread synchronously; will return immediately.
|
||||
// If the result isn't cached, will return `nil`; the caller should then pause playback, not increment frame counter and keep polling.
|
||||
// After an initial loading time, depending on `frameCacheSize`, frames should be available immediately from the cache.
|
||||
- (UIImage *)imageLazilyCachedAtIndex:(NSUInteger)index;
|
||||
|
||||
// Pass either a `UIImage` or an `FLAnimatedImage` and get back its size
|
||||
+ (CGSize)sizeForImage:(id)image;
|
||||
|
||||
// On success, the initializers return an `FLAnimatedImage` with all fields initialized, on failure they return `nil` and an error will be logged.
|
||||
- (instancetype)initWithAnimatedGIFData:(NSData *)data;
|
||||
// Pass 0 for optimalFrameCacheSize to get the default, predrawing is enabled by default.
|
||||
- (instancetype)initWithAnimatedGIFData:(NSData *)data optimalFrameCacheSize:(NSUInteger)optimalFrameCacheSize predrawingEnabled:(BOOL)isPredrawingEnabled NS_DESIGNATED_INITIALIZER;
|
||||
+ (instancetype)animatedImageWithGIFData:(NSData *)data;
|
||||
|
||||
@property (nonatomic, strong, readonly) NSData *data; // The data the receiver was initialized with; read-only
|
||||
|
||||
@end
|
||||
|
||||
typedef NS_ENUM(NSUInteger, FLLogLevel) {
|
||||
FLLogLevelNone = 0,
|
||||
FLLogLevelError,
|
||||
FLLogLevelWarn,
|
||||
FLLogLevelInfo,
|
||||
FLLogLevelDebug,
|
||||
FLLogLevelVerbose
|
||||
};
|
||||
|
||||
@interface FLAnimatedImage (Logging)
|
||||
|
||||
+ (void)setLogBlock:(void (^)(NSString *logString, FLLogLevel logLevel))logBlock logLevel:(FLLogLevel)logLevel;
|
||||
+ (void)logStringFromBlock:(NSString *(^)(void))stringBlock withLevel:(FLLogLevel)level;
|
||||
|
||||
@end
|
||||
|
||||
#define FLLog(logLevel, format, ...) [FLAnimatedImage logStringFromBlock:^NSString *{ return [NSString stringWithFormat:(format), ## __VA_ARGS__]; } withLevel:(logLevel)]
|
||||
|
||||
@interface FLWeakProxy : NSProxy
|
||||
|
||||
+ (instancetype)weakProxyForObject:(id)targetObject;
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,816 @@
|
||||
//
|
||||
// FLAnimatedImage.m
|
||||
// Flipboard
|
||||
//
|
||||
// Created by Raphael Schaad on 7/8/13.
|
||||
// Copyright (c) 2013-2015 Flipboard. All rights reserved.
|
||||
//
|
||||
|
||||
|
||||
#import "FLAnimatedImage.h"
|
||||
#import <ImageIO/ImageIO.h>
|
||||
#import <MobileCoreServices/MobileCoreServices.h>
|
||||
|
||||
|
||||
// From vm_param.h, define for iOS 8.0 or higher to build on device.
|
||||
#ifndef BYTE_SIZE
|
||||
#define BYTE_SIZE 8 // byte size in bits
|
||||
#endif
|
||||
|
||||
#define MEGABYTE (1024 * 1024)
|
||||
|
||||
// This is how the fastest browsers do it as per 2012: http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser-compatibility
|
||||
const NSTimeInterval kFLAnimatedImageDelayTimeIntervalMinimum = 0.02;
|
||||
|
||||
// An animated image's data size (dimensions * frameCount) category; its value is the max allowed memory (in MB).
|
||||
// E.g.: A 100x200px GIF with 30 frames is ~2.3MB in our pixel format and would fall into the `FLAnimatedImageDataSizeCategoryAll` category.
|
||||
typedef NS_ENUM(NSUInteger, FLAnimatedImageDataSizeCategory) {
|
||||
FLAnimatedImageDataSizeCategoryAll = 10, // All frames permanently in memory (be nice to the CPU)
|
||||
FLAnimatedImageDataSizeCategoryDefault = 75, // A frame cache of default size in memory (usually real-time performance and keeping low memory profile)
|
||||
FLAnimatedImageDataSizeCategoryOnDemand = 250, // Only keep one frame at the time in memory (easier on memory, slowest performance)
|
||||
FLAnimatedImageDataSizeCategoryUnsupported // Even for one frame too large, computer says no.
|
||||
};
|
||||
|
||||
typedef NS_ENUM(NSUInteger, FLAnimatedImageFrameCacheSize) {
|
||||
FLAnimatedImageFrameCacheSizeNoLimit = 0, // 0 means no specific limit
|
||||
FLAnimatedImageFrameCacheSizeLowMemory = 1, // The minimum frame cache size; this will produce frames on-demand.
|
||||
FLAnimatedImageFrameCacheSizeGrowAfterMemoryWarning = 2, // If we can produce the frames faster than we consume, one frame ahead will already result in a stutter-free playback.
|
||||
FLAnimatedImageFrameCacheSizeDefault = 5 // Build up a comfy buffer window to cope with CPU hiccups etc.
|
||||
};
|
||||
|
||||
|
||||
#if defined(DEBUG) && DEBUG
|
||||
@protocol FLAnimatedImageDebugDelegate <NSObject>
|
||||
@optional
|
||||
- (void)debug_animatedImage:(FLAnimatedImage *)animatedImage didUpdateCachedFrames:(NSIndexSet *)indexesOfFramesInCache;
|
||||
- (void)debug_animatedImage:(FLAnimatedImage *)animatedImage didRequestCachedFrame:(NSUInteger)index;
|
||||
- (CGFloat)debug_animatedImagePredrawingSlowdownFactor:(FLAnimatedImage *)animatedImage;
|
||||
@end
|
||||
#endif
|
||||
|
||||
|
||||
@interface FLAnimatedImage ()
|
||||
|
||||
@property (nonatomic, assign, readonly) NSUInteger frameCacheSizeOptimal; // The optimal number of frames to cache based on image size & number of frames; never changes
|
||||
@property (nonatomic, assign, readonly, getter=isPredrawingEnabled) BOOL predrawingEnabled; // Enables predrawing of images to improve performance.
|
||||
@property (nonatomic, assign) NSUInteger frameCacheSizeMaxInternal; // Allow to cap the cache size e.g. when memory warnings occur; 0 means no specific limit (default)
|
||||
@property (nonatomic, assign) NSUInteger requestedFrameIndex; // Most recently requested frame index
|
||||
@property (nonatomic, assign, readonly) NSUInteger posterImageFrameIndex; // Index of non-purgable poster image; never changes
|
||||
@property (nonatomic, strong, readonly) NSMutableDictionary *cachedFramesForIndexes;
|
||||
@property (nonatomic, strong, readonly) NSMutableIndexSet *cachedFrameIndexes; // Indexes of cached frames
|
||||
@property (nonatomic, strong, readonly) NSMutableIndexSet *requestedFrameIndexes; // Indexes of frames that are currently produced in the background
|
||||
@property (nonatomic, strong, readonly) NSIndexSet *allFramesIndexSet; // Default index set with the full range of indexes; never changes
|
||||
@property (nonatomic, assign) NSUInteger memoryWarningCount;
|
||||
@property (nonatomic, strong, readonly) dispatch_queue_t serialQueue;
|
||||
@property (nonatomic, strong, readonly) __attribute__((NSObject)) CGImageSourceRef imageSource;
|
||||
|
||||
// The weak proxy is used to break retain cycles with delayed actions from memory warnings.
|
||||
// We are lying about the actual type here to gain static type checking and eliminate casts.
|
||||
// The actual type of the object is `FLWeakProxy`.
|
||||
@property (nonatomic, strong, readonly) FLAnimatedImage *weakProxy;
|
||||
|
||||
#if defined(DEBUG) && DEBUG
|
||||
@property (nonatomic, weak) id<FLAnimatedImageDebugDelegate> debug_delegate;
|
||||
#endif
|
||||
|
||||
@end
|
||||
|
||||
|
||||
// For custom dispatching of memory warnings to avoid deallocation races since NSNotificationCenter doesn't retain objects it is notifying.
|
||||
static NSHashTable *allAnimatedImagesWeak;
|
||||
|
||||
@implementation FLAnimatedImage
|
||||
|
||||
#pragma mark - Accessors
|
||||
#pragma mark Public
|
||||
|
||||
// This is the definite value the frame cache needs to size itself to.
|
||||
- (NSUInteger)frameCacheSizeCurrent
|
||||
{
|
||||
NSUInteger frameCacheSizeCurrent = self.frameCacheSizeOptimal;
|
||||
|
||||
// If set, respect the caps.
|
||||
if (self.frameCacheSizeMax > FLAnimatedImageFrameCacheSizeNoLimit) {
|
||||
frameCacheSizeCurrent = MIN(frameCacheSizeCurrent, self.frameCacheSizeMax);
|
||||
}
|
||||
|
||||
if (self.frameCacheSizeMaxInternal > FLAnimatedImageFrameCacheSizeNoLimit) {
|
||||
frameCacheSizeCurrent = MIN(frameCacheSizeCurrent, self.frameCacheSizeMaxInternal);
|
||||
}
|
||||
|
||||
return frameCacheSizeCurrent;
|
||||
}
|
||||
|
||||
|
||||
- (void)setFrameCacheSizeMax:(NSUInteger)frameCacheSizeMax
|
||||
{
|
||||
if (_frameCacheSizeMax != frameCacheSizeMax) {
|
||||
|
||||
// Remember whether the new cap will cause the current cache size to shrink; then we'll make sure to purge from the cache if needed.
|
||||
BOOL willFrameCacheSizeShrink = (frameCacheSizeMax < self.frameCacheSizeCurrent);
|
||||
|
||||
// Update the value
|
||||
_frameCacheSizeMax = frameCacheSizeMax;
|
||||
|
||||
if (willFrameCacheSizeShrink) {
|
||||
[self purgeFrameCacheIfNeeded];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#pragma mark Private
|
||||
|
||||
- (void)setFrameCacheSizeMaxInternal:(NSUInteger)frameCacheSizeMaxInternal
|
||||
{
|
||||
if (_frameCacheSizeMaxInternal != frameCacheSizeMaxInternal) {
|
||||
|
||||
// Remember whether the new cap will cause the current cache size to shrink; then we'll make sure to purge from the cache if needed.
|
||||
BOOL willFrameCacheSizeShrink = (frameCacheSizeMaxInternal < self.frameCacheSizeCurrent);
|
||||
|
||||
// Update the value
|
||||
_frameCacheSizeMaxInternal = frameCacheSizeMaxInternal;
|
||||
|
||||
if (willFrameCacheSizeShrink) {
|
||||
[self purgeFrameCacheIfNeeded];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#pragma mark - Life Cycle
|
||||
|
||||
+ (void)initialize
|
||||
{
|
||||
if (self == [FLAnimatedImage class]) {
|
||||
// UIKit memory warning notification handler shared by all of the instances
|
||||
allAnimatedImagesWeak = [NSHashTable weakObjectsHashTable];
|
||||
|
||||
[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidReceiveMemoryWarningNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
|
||||
// UIKit notifications are posted on the main thread. didReceiveMemoryWarning: is expecting the main run loop, and we don't lock on allAnimatedImagesWeak
|
||||
NSAssert([NSThread isMainThread], @"Received memory warning on non-main thread");
|
||||
// Get a strong reference to all of the images. If an instance is returned in this array, it is still live and has not entered dealloc.
|
||||
// Note that FLAnimatedImages can be created on any thread, so the hash table must be locked.
|
||||
NSArray *images = nil;
|
||||
@synchronized(allAnimatedImagesWeak) {
|
||||
images = [[allAnimatedImagesWeak allObjects] copy];
|
||||
}
|
||||
// Now issue notifications to all of the images while holding a strong reference to them
|
||||
[images makeObjectsPerformSelector:@selector(didReceiveMemoryWarning:) withObject:note];
|
||||
}];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (instancetype)init
|
||||
{
|
||||
FLAnimatedImage *animatedImage = [self initWithAnimatedGIFData:nil];
|
||||
if (!animatedImage) {
|
||||
FLLog(FLLogLevelError, @"Use `-initWithAnimatedGIFData:` and supply the animated GIF data as an argument to initialize an object of type `FLAnimatedImage`.");
|
||||
}
|
||||
return animatedImage;
|
||||
}
|
||||
|
||||
|
||||
- (instancetype)initWithAnimatedGIFData:(NSData *)data
|
||||
{
|
||||
return [self initWithAnimatedGIFData:data optimalFrameCacheSize:0 predrawingEnabled:YES];
|
||||
}
|
||||
|
||||
- (instancetype)initWithAnimatedGIFData:(NSData *)data optimalFrameCacheSize:(NSUInteger)optimalFrameCacheSize predrawingEnabled:(BOOL)isPredrawingEnabled
|
||||
{
|
||||
// Early return if no data supplied!
|
||||
BOOL hasData = ([data length] > 0);
|
||||
if (!hasData) {
|
||||
FLLog(FLLogLevelError, @"No animated GIF data supplied.");
|
||||
return nil;
|
||||
}
|
||||
|
||||
self = [super init];
|
||||
if (self) {
|
||||
// Do one-time initializations of `readonly` properties directly to ivar to prevent implicit actions and avoid need for private `readwrite` property overrides.
|
||||
|
||||
// Keep a strong reference to `data` and expose it read-only publicly.
|
||||
// However, we will use the `_imageSource` as handler to the image data throughout our life cycle.
|
||||
_data = data;
|
||||
_predrawingEnabled = isPredrawingEnabled;
|
||||
|
||||
// Initialize internal data structures
|
||||
_cachedFramesForIndexes = [[NSMutableDictionary alloc] init];
|
||||
_cachedFrameIndexes = [[NSMutableIndexSet alloc] init];
|
||||
_requestedFrameIndexes = [[NSMutableIndexSet alloc] init];
|
||||
|
||||
// Note: We could leverage `CGImageSourceCreateWithURL` too to add a second initializer `-initWithAnimatedGIFContentsOfURL:`.
|
||||
_imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)data,
|
||||
(__bridge CFDictionaryRef)@{(NSString *)kCGImageSourceShouldCache: @NO});
|
||||
// Early return on failure!
|
||||
if (!_imageSource) {
|
||||
FLLog(FLLogLevelError, @"Failed to `CGImageSourceCreateWithData` for animated GIF data %@", data);
|
||||
return nil;
|
||||
}
|
||||
|
||||
// Early return if not GIF!
|
||||
CFStringRef imageSourceContainerType = CGImageSourceGetType(_imageSource);
|
||||
BOOL isGIFData = UTTypeConformsTo(imageSourceContainerType, kUTTypeGIF);
|
||||
if (!isGIFData) {
|
||||
FLLog(FLLogLevelError, @"Supplied data is of type %@ and doesn't seem to be GIF data %@", imageSourceContainerType, data);
|
||||
return nil;
|
||||
}
|
||||
|
||||
// Get `LoopCount`
|
||||
// Note: 0 means repeating the animation indefinitely.
|
||||
// Image properties example:
|
||||
// {
|
||||
// FileSize = 314446;
|
||||
// "{GIF}" = {
|
||||
// HasGlobalColorMap = 1;
|
||||
// LoopCount = 0;
|
||||
// };
|
||||
// }
|
||||
NSDictionary *imageProperties = (__bridge_transfer NSDictionary *)CGImageSourceCopyProperties(_imageSource, NULL);
|
||||
_loopCount = [[[imageProperties objectForKey:(id)kCGImagePropertyGIFDictionary] objectForKey:(id)kCGImagePropertyGIFLoopCount] unsignedIntegerValue];
|
||||
|
||||
// Iterate through frame images
|
||||
size_t imageCount = CGImageSourceGetCount(_imageSource);
|
||||
NSUInteger skippedFrameCount = 0;
|
||||
NSMutableDictionary *delayTimesForIndexesMutable = [NSMutableDictionary dictionaryWithCapacity:imageCount];
|
||||
for (size_t i = 0; i < imageCount; i++) {
|
||||
@autoreleasepool {
|
||||
CGImageRef frameImageRef = CGImageSourceCreateImageAtIndex(_imageSource, i, NULL);
|
||||
if (frameImageRef) {
|
||||
UIImage *frameImage = [UIImage imageWithCGImage:frameImageRef];
|
||||
// Check for valid `frameImage` before parsing its properties as frames can be corrupted (and `frameImage` even `nil` when `frameImageRef` was valid).
|
||||
if (frameImage) {
|
||||
// Set poster image
|
||||
if (!self.posterImage) {
|
||||
_posterImage = frameImage;
|
||||
// Set its size to proxy our size.
|
||||
_size = _posterImage.size;
|
||||
// Remember index of poster image so we never purge it; also add it to the cache.
|
||||
_posterImageFrameIndex = i;
|
||||
[self.cachedFramesForIndexes setObject:self.posterImage forKey:@(self.posterImageFrameIndex)];
|
||||
[self.cachedFrameIndexes addIndex:self.posterImageFrameIndex];
|
||||
}
|
||||
|
||||
// Get `DelayTime`
|
||||
// Note: It's not in (1/100) of a second like still falsely described in the documentation as per iOS 8 (rdar://19507384) but in seconds stored as `kCFNumberFloat32Type`.
|
||||
// Frame properties example:
|
||||
// {
|
||||
// ColorModel = RGB;
|
||||
// Depth = 8;
|
||||
// PixelHeight = 960;
|
||||
// PixelWidth = 640;
|
||||
// "{GIF}" = {
|
||||
// DelayTime = "0.4";
|
||||
// UnclampedDelayTime = "0.4";
|
||||
// };
|
||||
// }
|
||||
|
||||
NSDictionary *frameProperties = (__bridge_transfer NSDictionary *)CGImageSourceCopyPropertiesAtIndex(_imageSource, i, NULL);
|
||||
NSDictionary *framePropertiesGIF = [frameProperties objectForKey:(id)kCGImagePropertyGIFDictionary];
|
||||
|
||||
// Try to use the unclamped delay time; fall back to the normal delay time.
|
||||
NSNumber *delayTime = [framePropertiesGIF objectForKey:(id)kCGImagePropertyGIFUnclampedDelayTime];
|
||||
if (!delayTime) {
|
||||
delayTime = [framePropertiesGIF objectForKey:(id)kCGImagePropertyGIFDelayTime];
|
||||
}
|
||||
// If we don't get a delay time from the properties, fall back to `kDelayTimeIntervalDefault` or carry over the preceding frame's value.
|
||||
const NSTimeInterval kDelayTimeIntervalDefault = 0.1;
|
||||
if (!delayTime) {
|
||||
if (i == 0) {
|
||||
FLLog(FLLogLevelInfo, @"Falling back to default delay time for first frame %@ because none found in GIF properties %@", frameImage, frameProperties);
|
||||
delayTime = @(kDelayTimeIntervalDefault);
|
||||
} else {
|
||||
FLLog(FLLogLevelInfo, @"Falling back to preceding delay time for frame %zu %@ because none found in GIF properties %@", i, frameImage, frameProperties);
|
||||
delayTime = delayTimesForIndexesMutable[@(i - 1)];
|
||||
}
|
||||
}
|
||||
// Support frame delays as low as `kFLAnimatedImageDelayTimeIntervalMinimum`, with anything below being rounded up to `kDelayTimeIntervalDefault` for legacy compatibility.
|
||||
// To support the minimum even when rounding errors occur, use an epsilon when comparing. We downcast to float because that's what we get for delayTime from ImageIO.
|
||||
if ([delayTime floatValue] < ((float)kFLAnimatedImageDelayTimeIntervalMinimum - FLT_EPSILON)) {
|
||||
FLLog(FLLogLevelInfo, @"Rounding frame %zu's `delayTime` from %f up to default %f (minimum supported: %f).", i, [delayTime floatValue], kDelayTimeIntervalDefault, kFLAnimatedImageDelayTimeIntervalMinimum);
|
||||
delayTime = @(kDelayTimeIntervalDefault);
|
||||
}
|
||||
delayTimesForIndexesMutable[@(i)] = delayTime;
|
||||
} else {
|
||||
skippedFrameCount++;
|
||||
FLLog(FLLogLevelInfo, @"Dropping frame %zu because valid `CGImageRef` %@ did result in `nil`-`UIImage`.", i, frameImageRef);
|
||||
}
|
||||
CFRelease(frameImageRef);
|
||||
} else {
|
||||
skippedFrameCount++;
|
||||
FLLog(FLLogLevelInfo, @"Dropping frame %zu because failed to `CGImageSourceCreateImageAtIndex` with image source %@", i, _imageSource);
|
||||
}
|
||||
}
|
||||
}
|
||||
_delayTimesForIndexes = [delayTimesForIndexesMutable copy];
|
||||
_frameCount = imageCount;
|
||||
|
||||
if (self.frameCount == 0) {
|
||||
FLLog(FLLogLevelInfo, @"Failed to create any valid frames for GIF with properties %@", imageProperties);
|
||||
return nil;
|
||||
} else if (self.frameCount == 1) {
|
||||
// Warn when we only have a single frame but return a valid GIF.
|
||||
FLLog(FLLogLevelInfo, @"Created valid GIF but with only a single frame. Image properties: %@", imageProperties);
|
||||
} else {
|
||||
// We have multiple frames, rock on!
|
||||
}
|
||||
|
||||
// If no value is provided, select a default based on the GIF.
|
||||
if (optimalFrameCacheSize == 0) {
|
||||
// Calculate the optimal frame cache size: try choosing a larger buffer window depending on the predicted image size.
|
||||
// It's only dependent on the image size & number of frames and never changes.
|
||||
CGFloat animatedImageDataSize = CGImageGetBytesPerRow(self.posterImage.CGImage) * self.size.height * (self.frameCount - skippedFrameCount) / MEGABYTE;
|
||||
if (animatedImageDataSize <= FLAnimatedImageDataSizeCategoryAll) {
|
||||
_frameCacheSizeOptimal = self.frameCount;
|
||||
} else if (animatedImageDataSize <= FLAnimatedImageDataSizeCategoryDefault) {
|
||||
// This value doesn't depend on device memory much because if we're not keeping all frames in memory we will always be decoding 1 frame up ahead per 1 frame that gets played and at this point we might as well just keep a small buffer just large enough to keep from running out of frames.
|
||||
_frameCacheSizeOptimal = FLAnimatedImageFrameCacheSizeDefault;
|
||||
} else {
|
||||
// The predicted size exceeds the limits to build up a cache and we go into low memory mode from the beginning.
|
||||
_frameCacheSizeOptimal = FLAnimatedImageFrameCacheSizeLowMemory;
|
||||
}
|
||||
} else {
|
||||
// Use the provided value.
|
||||
_frameCacheSizeOptimal = optimalFrameCacheSize;
|
||||
}
|
||||
// In any case, cap the optimal cache size at the frame count.
|
||||
_frameCacheSizeOptimal = MIN(_frameCacheSizeOptimal, self.frameCount);
|
||||
|
||||
// Convenience/minor performance optimization; keep an index set handy with the full range to return in `-frameIndexesToCache`.
|
||||
_allFramesIndexSet = [[NSIndexSet alloc] initWithIndexesInRange:NSMakeRange(0, self.frameCount)];
|
||||
|
||||
// See the property declarations for descriptions.
|
||||
_weakProxy = (id)[FLWeakProxy weakProxyForObject:self];
|
||||
|
||||
// Register this instance in the weak table for memory notifications. The NSHashTable will clean up after itself when we're gone.
|
||||
// Note that FLAnimatedImages can be created on any thread, so the hash table must be locked.
|
||||
@synchronized(allAnimatedImagesWeak) {
|
||||
[allAnimatedImagesWeak addObject:self];
|
||||
}
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
+ (instancetype)animatedImageWithGIFData:(NSData *)data
|
||||
{
|
||||
FLAnimatedImage *animatedImage = [[FLAnimatedImage alloc] initWithAnimatedGIFData:data];
|
||||
return animatedImage;
|
||||
}
|
||||
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
if (_weakProxy) {
|
||||
[NSObject cancelPreviousPerformRequestsWithTarget:_weakProxy];
|
||||
}
|
||||
|
||||
if (_imageSource) {
|
||||
CFRelease(_imageSource);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#pragma mark - Public Methods
|
||||
|
||||
// See header for more details.
|
||||
// Note: both consumer and producer are throttled: consumer by frame timings and producer by the available memory (max buffer window size).
|
||||
- (UIImage *)imageLazilyCachedAtIndex:(NSUInteger)index
|
||||
{
|
||||
// Early return if the requested index is beyond bounds.
|
||||
// Note: We're comparing an index with a count and need to bail on greater than or equal to.
|
||||
if (index >= self.frameCount) {
|
||||
FLLog(FLLogLevelWarn, @"Skipping requested frame %lu beyond bounds (total frame count: %lu) for animated image: %@", (unsigned long)index, (unsigned long)self.frameCount, self);
|
||||
return nil;
|
||||
}
|
||||
|
||||
// Remember requested frame index, this influences what we should cache next.
|
||||
self.requestedFrameIndex = index;
|
||||
#if defined(DEBUG) && DEBUG
|
||||
if ([self.debug_delegate respondsToSelector:@selector(debug_animatedImage:didRequestCachedFrame:)]) {
|
||||
[self.debug_delegate debug_animatedImage:self didRequestCachedFrame:index];
|
||||
}
|
||||
#endif
|
||||
|
||||
// Quick check to avoid doing any work if we already have all possible frames cached, a common case.
|
||||
if ([self.cachedFrameIndexes count] < self.frameCount) {
|
||||
// If we have frames that should be cached but aren't and aren't requested yet, request them.
|
||||
// Exclude existing cached frames, frames already requested, and specially cached poster image.
|
||||
NSMutableIndexSet *frameIndexesToAddToCacheMutable = [self frameIndexesToCache];
|
||||
[frameIndexesToAddToCacheMutable removeIndexes:self.cachedFrameIndexes];
|
||||
[frameIndexesToAddToCacheMutable removeIndexes:self.requestedFrameIndexes];
|
||||
[frameIndexesToAddToCacheMutable removeIndex:self.posterImageFrameIndex];
|
||||
NSIndexSet *frameIndexesToAddToCache = [frameIndexesToAddToCacheMutable copy];
|
||||
|
||||
// Asynchronously add frames to our cache.
|
||||
if ([frameIndexesToAddToCache count] > 0) {
|
||||
[self addFrameIndexesToCache:frameIndexesToAddToCache];
|
||||
}
|
||||
}
|
||||
|
||||
// Get the specified image.
|
||||
UIImage *image = self.cachedFramesForIndexes[@(index)];
|
||||
|
||||
// Purge if needed based on the current playhead position.
|
||||
[self purgeFrameCacheIfNeeded];
|
||||
|
||||
return image;
|
||||
}
|
||||
|
||||
|
||||
// Only called once from `-imageLazilyCachedAtIndex` but factored into its own method for logical grouping.
|
||||
- (void)addFrameIndexesToCache:(NSIndexSet *)frameIndexesToAddToCache
|
||||
{
|
||||
// Order matters. First, iterate over the indexes starting from the requested frame index.
|
||||
// Then, if there are any indexes before the requested frame index, do those.
|
||||
NSRange firstRange = NSMakeRange(self.requestedFrameIndex, self.frameCount - self.requestedFrameIndex);
|
||||
NSRange secondRange = NSMakeRange(0, self.requestedFrameIndex);
|
||||
if (firstRange.length + secondRange.length != self.frameCount) {
|
||||
FLLog(FLLogLevelWarn, @"Two-part frame cache range doesn't equal full range.");
|
||||
}
|
||||
|
||||
// Add to the requested list before we actually kick them off, so they don't get into the queue twice.
|
||||
[self.requestedFrameIndexes addIndexes:frameIndexesToAddToCache];
|
||||
|
||||
// Lazily create dedicated isolation queue.
|
||||
if (!self.serialQueue) {
|
||||
_serialQueue = dispatch_queue_create("com.flipboard.framecachingqueue", DISPATCH_QUEUE_SERIAL);
|
||||
}
|
||||
|
||||
// Start streaming requested frames in the background into the cache.
|
||||
// Avoid capturing self in the block as there's no reason to keep doing work if the animated image went away.
|
||||
FLAnimatedImage * __weak weakSelf = self;
|
||||
dispatch_async(self.serialQueue, ^{
|
||||
// Produce and cache next needed frame.
|
||||
void (^frameRangeBlock)(NSRange, BOOL *) = ^(NSRange range, BOOL *stop) {
|
||||
// Iterate through contiguous indexes; can be faster than `enumerateIndexesInRange:options:usingBlock:`.
|
||||
for (NSUInteger i = range.location; i < NSMaxRange(range); i++) {
|
||||
#if defined(DEBUG) && DEBUG
|
||||
CFTimeInterval predrawBeginTime = CACurrentMediaTime();
|
||||
#endif
|
||||
UIImage *image = [weakSelf imageAtIndex:i];
|
||||
#if defined(DEBUG) && DEBUG
|
||||
CFTimeInterval predrawDuration = CACurrentMediaTime() - predrawBeginTime;
|
||||
CFTimeInterval slowdownDuration = 0.0;
|
||||
if ([self.debug_delegate respondsToSelector:@selector(debug_animatedImagePredrawingSlowdownFactor:)]) {
|
||||
CGFloat predrawingSlowdownFactor = [self.debug_delegate debug_animatedImagePredrawingSlowdownFactor:self];
|
||||
slowdownDuration = predrawDuration * predrawingSlowdownFactor - predrawDuration;
|
||||
[NSThread sleepForTimeInterval:slowdownDuration];
|
||||
}
|
||||
FLLog(FLLogLevelVerbose, @"Predrew frame %lu in %f ms for animated image: %@", (unsigned long)i, (predrawDuration + slowdownDuration) * 1000, self);
|
||||
#endif
|
||||
// The results get returned one by one as soon as they're ready (and not in batch).
|
||||
// The benefits of having the first frames as quick as possible outweigh building up a buffer to cope with potential hiccups when the CPU suddenly gets busy.
|
||||
if (image && weakSelf) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
weakSelf.cachedFramesForIndexes[@(i)] = image;
|
||||
[weakSelf.cachedFrameIndexes addIndex:i];
|
||||
[weakSelf.requestedFrameIndexes removeIndex:i];
|
||||
#if defined(DEBUG) && DEBUG
|
||||
if ([weakSelf.debug_delegate respondsToSelector:@selector(debug_animatedImage:didUpdateCachedFrames:)]) {
|
||||
[weakSelf.debug_delegate debug_animatedImage:weakSelf didUpdateCachedFrames:weakSelf.cachedFrameIndexes];
|
||||
}
|
||||
#endif
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
[frameIndexesToAddToCache enumerateRangesInRange:firstRange options:0 usingBlock:frameRangeBlock];
|
||||
[frameIndexesToAddToCache enumerateRangesInRange:secondRange options:0 usingBlock:frameRangeBlock];
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+ (CGSize)sizeForImage:(id)image
|
||||
{
|
||||
CGSize imageSize = CGSizeZero;
|
||||
|
||||
// Early return for nil
|
||||
if (!image) {
|
||||
return imageSize;
|
||||
}
|
||||
|
||||
if ([image isKindOfClass:[UIImage class]]) {
|
||||
UIImage *uiImage = (UIImage *)image;
|
||||
imageSize = uiImage.size;
|
||||
} else if ([image isKindOfClass:[FLAnimatedImage class]]) {
|
||||
FLAnimatedImage *animatedImage = (FLAnimatedImage *)image;
|
||||
imageSize = animatedImage.size;
|
||||
} else {
|
||||
// Bear trap to capture bad images; we have seen crashers cropping up on iOS 7.
|
||||
FLLog(FLLogLevelError, @"`image` isn't of expected types `UIImage` or `FLAnimatedImage`: %@", image);
|
||||
}
|
||||
|
||||
return imageSize;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark - Private Methods
|
||||
#pragma mark Frame Loading
|
||||
|
||||
- (UIImage *)imageAtIndex:(NSUInteger)index
|
||||
{
|
||||
// It's very important to use the cached `_imageSource` since the random access to a frame with `CGImageSourceCreateImageAtIndex` turns from an O(1) into an O(n) operation when re-initializing the image source every time.
|
||||
CGImageRef imageRef = CGImageSourceCreateImageAtIndex(_imageSource, index, NULL);
|
||||
|
||||
// Early return for nil
|
||||
if (!imageRef) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
UIImage *image = [UIImage imageWithCGImage:imageRef];
|
||||
CFRelease(imageRef);
|
||||
|
||||
// Loading in the image object is only half the work, the displaying image view would still have to synchronosly wait and decode the image, so we go ahead and do that here on the background thread.
|
||||
if (self.isPredrawingEnabled) {
|
||||
image = [[self class] predrawnImageFromImage:image];
|
||||
}
|
||||
|
||||
return image;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark Frame Caching
|
||||
|
||||
- (NSMutableIndexSet *)frameIndexesToCache
|
||||
{
|
||||
NSMutableIndexSet *indexesToCache = nil;
|
||||
// Quick check to avoid building the index set if the number of frames to cache equals the total frame count.
|
||||
if (self.frameCacheSizeCurrent == self.frameCount) {
|
||||
indexesToCache = [self.allFramesIndexSet mutableCopy];
|
||||
} else {
|
||||
indexesToCache = [[NSMutableIndexSet alloc] init];
|
||||
|
||||
// Add indexes to the set in two separate blocks- the first starting from the requested frame index, up to the limit or the end.
|
||||
// The second, if needed, the remaining number of frames beginning at index zero.
|
||||
NSUInteger firstLength = MIN(self.frameCacheSizeCurrent, self.frameCount - self.requestedFrameIndex);
|
||||
NSRange firstRange = NSMakeRange(self.requestedFrameIndex, firstLength);
|
||||
[indexesToCache addIndexesInRange:firstRange];
|
||||
NSUInteger secondLength = self.frameCacheSizeCurrent - firstLength;
|
||||
if (secondLength > 0) {
|
||||
NSRange secondRange = NSMakeRange(0, secondLength);
|
||||
[indexesToCache addIndexesInRange:secondRange];
|
||||
}
|
||||
// Double check our math, before we add the poster image index which may increase it by one.
|
||||
if ([indexesToCache count] != self.frameCacheSizeCurrent) {
|
||||
FLLog(FLLogLevelWarn, @"Number of frames to cache doesn't equal expected cache size.");
|
||||
}
|
||||
|
||||
[indexesToCache addIndex:self.posterImageFrameIndex];
|
||||
}
|
||||
|
||||
return indexesToCache;
|
||||
}
|
||||
|
||||
|
||||
- (void)purgeFrameCacheIfNeeded
|
||||
{
|
||||
// Purge frames that are currently cached but don't need to be.
|
||||
// But not if we're still under the number of frames to cache.
|
||||
// This way, if all frames are allowed to be cached (the common case), we can skip all the `NSIndexSet` math below.
|
||||
if ([self.cachedFrameIndexes count] > self.frameCacheSizeCurrent) {
|
||||
NSMutableIndexSet *indexesToPurge = [self.cachedFrameIndexes mutableCopy];
|
||||
[indexesToPurge removeIndexes:[self frameIndexesToCache]];
|
||||
[indexesToPurge enumerateRangesUsingBlock:^(NSRange range, BOOL *stop) {
|
||||
// Iterate through contiguous indexes; can be faster than `enumerateIndexesInRange:options:usingBlock:`.
|
||||
for (NSUInteger i = range.location; i < NSMaxRange(range); i++) {
|
||||
[self.cachedFrameIndexes removeIndex:i];
|
||||
[self.cachedFramesForIndexes removeObjectForKey:@(i)];
|
||||
// Note: Don't `CGImageSourceRemoveCacheAtIndex` on the image source for frames that we don't want cached any longer to maintain O(1) time access.
|
||||
#if defined(DEBUG) && DEBUG
|
||||
if ([self.debug_delegate respondsToSelector:@selector(debug_animatedImage:didUpdateCachedFrames:)]) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self.debug_delegate debug_animatedImage:self didUpdateCachedFrames:self.cachedFrameIndexes];
|
||||
});
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (void)growFrameCacheSizeAfterMemoryWarning:(NSNumber *)frameCacheSize
|
||||
{
|
||||
self.frameCacheSizeMaxInternal = [frameCacheSize unsignedIntegerValue];
|
||||
FLLog(FLLogLevelDebug, @"Grew frame cache size max to %lu after memory warning for animated image: %@", (unsigned long)self.frameCacheSizeMaxInternal, self);
|
||||
|
||||
// Schedule resetting the frame cache size max completely after a while.
|
||||
const NSTimeInterval kResetDelay = 3.0;
|
||||
[self.weakProxy performSelector:@selector(resetFrameCacheSizeMaxInternal) withObject:nil afterDelay:kResetDelay];
|
||||
}
|
||||
|
||||
|
||||
- (void)resetFrameCacheSizeMaxInternal
|
||||
{
|
||||
self.frameCacheSizeMaxInternal = FLAnimatedImageFrameCacheSizeNoLimit;
|
||||
FLLog(FLLogLevelDebug, @"Reset frame cache size max (current frame cache size: %lu) for animated image: %@", (unsigned long)self.frameCacheSizeCurrent, self);
|
||||
}
|
||||
|
||||
|
||||
#pragma mark System Memory Warnings Notification Handler
|
||||
|
||||
- (void)didReceiveMemoryWarning:(NSNotification *)notification
|
||||
{
|
||||
self.memoryWarningCount++;
|
||||
|
||||
// If we were about to grow larger, but got rapped on our knuckles by the system again, cancel.
|
||||
[NSObject cancelPreviousPerformRequestsWithTarget:self.weakProxy selector:@selector(growFrameCacheSizeAfterMemoryWarning:) object:@(FLAnimatedImageFrameCacheSizeGrowAfterMemoryWarning)];
|
||||
[NSObject cancelPreviousPerformRequestsWithTarget:self.weakProxy selector:@selector(resetFrameCacheSizeMaxInternal) object:nil];
|
||||
|
||||
// Go down to the minimum and by that implicitly immediately purge from the cache if needed to not get jettisoned by the system and start producing frames on-demand.
|
||||
FLLog(FLLogLevelDebug, @"Attempt setting frame cache size max to %lu (previous was %lu) after memory warning #%lu for animated image: %@", (unsigned long)FLAnimatedImageFrameCacheSizeLowMemory, (unsigned long)self.frameCacheSizeMaxInternal, (unsigned long)self.memoryWarningCount, self);
|
||||
self.frameCacheSizeMaxInternal = FLAnimatedImageFrameCacheSizeLowMemory;
|
||||
|
||||
// Schedule growing larger again after a while, but cap our attempts to prevent a periodic sawtooth wave (ramps upward and then sharply drops) of memory usage.
|
||||
//
|
||||
// [mem]^ (2) (5) (6) 1) Loading frames for the first time
|
||||
// (*)| , , , 2) Mem warning #1; purge cache
|
||||
// | /| (4)/| /| 3) Grow cache size a bit after a while, if no mem warning occurs
|
||||
// | / | _/ | _/ | 4) Try to grow cache size back to optimum after a while, if no mem warning occurs
|
||||
// |(1)/ |_/ |/ |__(7) 5) Mem warning #2; purge cache
|
||||
// |__/ (3) 6) After repetition of (3) and (4), mem warning #3; purge cache
|
||||
// +----------------------> 7) After 3 mem warnings, stay at minimum cache size
|
||||
// [t]
|
||||
// *) The mem high water mark before we get warned might change for every cycle.
|
||||
//
|
||||
const NSUInteger kGrowAttemptsMax = 2;
|
||||
const NSTimeInterval kGrowDelay = 2.0;
|
||||
if ((self.memoryWarningCount - 1) <= kGrowAttemptsMax) {
|
||||
[self.weakProxy performSelector:@selector(growFrameCacheSizeAfterMemoryWarning:) withObject:@(FLAnimatedImageFrameCacheSizeGrowAfterMemoryWarning) afterDelay:kGrowDelay];
|
||||
}
|
||||
|
||||
// Note: It's not possible to get the level of a memory warning with a public API: http://stackoverflow.com/questions/2915247/iphone-os-memory-warnings-what-do-the-different-levels-mean/2915477#2915477
|
||||
}
|
||||
|
||||
|
||||
#pragma mark Image Decoding
|
||||
|
||||
// Decodes the image's data and draws it off-screen fully in memory; it's thread-safe and hence can be called on a background thread.
|
||||
// On success, the returned object is a new `UIImage` instance with the same content as the one passed in.
|
||||
// On failure, the returned object is the unchanged passed in one; the data will not be predrawn in memory though and an error will be logged.
|
||||
// First inspired by & good Karma to: https://gist.github.com/steipete/1144242
|
||||
+ (UIImage *)predrawnImageFromImage:(UIImage *)imageToPredraw
|
||||
{
|
||||
// Always use a device RGB color space for simplicity and predictability what will be going on.
|
||||
CGColorSpaceRef colorSpaceDeviceRGBRef = CGColorSpaceCreateDeviceRGB();
|
||||
// Early return on failure!
|
||||
if (!colorSpaceDeviceRGBRef) {
|
||||
FLLog(FLLogLevelError, @"Failed to `CGColorSpaceCreateDeviceRGB` for image %@", imageToPredraw);
|
||||
return imageToPredraw;
|
||||
}
|
||||
|
||||
// Even when the image doesn't have transparency, we have to add the extra channel because Quartz doesn't support other pixel formats than 32 bpp/8 bpc for RGB:
|
||||
// kCGImageAlphaNoneSkipFirst, kCGImageAlphaNoneSkipLast, kCGImageAlphaPremultipliedFirst, kCGImageAlphaPremultipliedLast
|
||||
// (source: docs "Quartz 2D Programming Guide > Graphics Contexts > Table 2-1 Pixel formats supported for bitmap graphics contexts")
|
||||
size_t numberOfComponents = CGColorSpaceGetNumberOfComponents(colorSpaceDeviceRGBRef) + 1; // 4: RGB + A
|
||||
|
||||
// "In iOS 4.0 and later, and OS X v10.6 and later, you can pass NULL if you want Quartz to allocate memory for the bitmap." (source: docs)
|
||||
void *data = NULL;
|
||||
size_t width = imageToPredraw.size.width;
|
||||
size_t height = imageToPredraw.size.height;
|
||||
size_t bitsPerComponent = CHAR_BIT;
|
||||
|
||||
size_t bitsPerPixel = (bitsPerComponent * numberOfComponents);
|
||||
size_t bytesPerPixel = (bitsPerPixel / BYTE_SIZE);
|
||||
size_t bytesPerRow = (bytesPerPixel * width);
|
||||
|
||||
CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
|
||||
|
||||
CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageToPredraw.CGImage);
|
||||
// If the alpha info doesn't match to one of the supported formats (see above), pick a reasonable supported one.
|
||||
// "For bitmaps created in iOS 3.2 and later, the drawing environment uses the premultiplied ARGB format to store the bitmap data." (source: docs)
|
||||
if (alphaInfo == kCGImageAlphaNone || alphaInfo == kCGImageAlphaOnly) {
|
||||
alphaInfo = kCGImageAlphaNoneSkipFirst;
|
||||
} else if (alphaInfo == kCGImageAlphaFirst) {
|
||||
alphaInfo = kCGImageAlphaPremultipliedFirst;
|
||||
} else if (alphaInfo == kCGImageAlphaLast) {
|
||||
alphaInfo = kCGImageAlphaPremultipliedLast;
|
||||
}
|
||||
// "The constants for specifying the alpha channel information are declared with the `CGImageAlphaInfo` type but can be passed to this parameter safely." (source: docs)
|
||||
bitmapInfo |= alphaInfo;
|
||||
|
||||
// Create our own graphics context to draw to; `UIGraphicsGetCurrentContext`/`UIGraphicsBeginImageContextWithOptions` doesn't create a new context but returns the current one which isn't thread-safe (e.g. main thread could use it at the same time).
|
||||
// Note: It's not worth caching the bitmap context for multiple frames ("unique key" would be `width`, `height` and `hasAlpha`), it's ~50% slower. Time spent in libRIP's `CGSBlendBGRA8888toARGB8888` suddenly shoots up -- not sure why.
|
||||
CGContextRef bitmapContextRef = CGBitmapContextCreate(data, width, height, bitsPerComponent, bytesPerRow, colorSpaceDeviceRGBRef, bitmapInfo);
|
||||
CGColorSpaceRelease(colorSpaceDeviceRGBRef);
|
||||
// Early return on failure!
|
||||
if (!bitmapContextRef) {
|
||||
FLLog(FLLogLevelError, @"Failed to `CGBitmapContextCreate` with color space %@ and parameters (width: %zu height: %zu bitsPerComponent: %zu bytesPerRow: %zu) for image %@", colorSpaceDeviceRGBRef, width, height, bitsPerComponent, bytesPerRow, imageToPredraw);
|
||||
return imageToPredraw;
|
||||
}
|
||||
|
||||
// Draw image in bitmap context and create image by preserving receiver's properties.
|
||||
CGContextDrawImage(bitmapContextRef, CGRectMake(0.0, 0.0, imageToPredraw.size.width, imageToPredraw.size.height), imageToPredraw.CGImage);
|
||||
CGImageRef predrawnImageRef = CGBitmapContextCreateImage(bitmapContextRef);
|
||||
UIImage *predrawnImage = [UIImage imageWithCGImage:predrawnImageRef scale:imageToPredraw.scale orientation:imageToPredraw.imageOrientation];
|
||||
CGImageRelease(predrawnImageRef);
|
||||
CGContextRelease(bitmapContextRef);
|
||||
|
||||
// Early return on failure!
|
||||
if (!predrawnImage) {
|
||||
FLLog(FLLogLevelError, @"Failed to `imageWithCGImage:scale:orientation:` with image ref %@ created with color space %@ and bitmap context %@ and properties and properties (scale: %f orientation: %ld) for image %@", predrawnImageRef, colorSpaceDeviceRGBRef, bitmapContextRef, imageToPredraw.scale, (long)imageToPredraw.imageOrientation, imageToPredraw);
|
||||
return imageToPredraw;
|
||||
}
|
||||
|
||||
return predrawnImage;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark - Description
|
||||
|
||||
- (NSString *)description
|
||||
{
|
||||
NSString *description = [super description];
|
||||
|
||||
description = [description stringByAppendingFormat:@" size=%@", NSStringFromCGSize(self.size)];
|
||||
description = [description stringByAppendingFormat:@" frameCount=%lu", (unsigned long)self.frameCount];
|
||||
|
||||
return description;
|
||||
}
|
||||
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark - Logging
|
||||
|
||||
@implementation FLAnimatedImage (Logging)
|
||||
|
||||
static void (^_logBlock)(NSString *logString, FLLogLevel logLevel) = nil;
|
||||
static FLLogLevel _logLevel;
|
||||
|
||||
+ (void)setLogBlock:(void (^)(NSString *logString, FLLogLevel logLevel))logBlock logLevel:(FLLogLevel)logLevel
|
||||
{
|
||||
_logBlock = logBlock;
|
||||
_logLevel = logLevel;
|
||||
}
|
||||
|
||||
+ (void)logStringFromBlock:(NSString *(^)(void))stringBlock withLevel:(FLLogLevel)level
|
||||
{
|
||||
if (level <= _logLevel && _logBlock && stringBlock) {
|
||||
_logBlock(stringBlock(), level);
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
#pragma mark - FLWeakProxy
|
||||
|
||||
@interface FLWeakProxy ()
|
||||
|
||||
@property (nonatomic, weak) id target;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation FLWeakProxy
|
||||
|
||||
#pragma mark Life Cycle
|
||||
|
||||
// This is the designated creation method of an `FLWeakProxy` and
|
||||
// as a subclass of `NSProxy` it doesn't respond to or need `-init`.
|
||||
+ (instancetype)weakProxyForObject:(id)targetObject
|
||||
{
|
||||
FLWeakProxy *weakProxy = [FLWeakProxy alloc];
|
||||
weakProxy.target = targetObject;
|
||||
return weakProxy;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark Forwarding Messages
|
||||
|
||||
- (id)forwardingTargetForSelector:(SEL)selector
|
||||
{
|
||||
// Keep it lightweight: access the ivar directly
|
||||
return _target;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark - NSWeakProxy Method Overrides
|
||||
#pragma mark Handling Unimplemented Methods
|
||||
|
||||
- (void)forwardInvocation:(NSInvocation *)invocation
|
||||
{
|
||||
// Fallback for when target is nil. Don't do anything, just return 0/NULL/nil.
|
||||
// The method signature we've received to get here is just a dummy to keep `doesNotRecognizeSelector:` from firing.
|
||||
// We can't really handle struct return types here because we don't know the length.
|
||||
void *nullPointer = NULL;
|
||||
[invocation setReturnValue:&nullPointer];
|
||||
}
|
||||
|
||||
|
||||
- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
|
||||
{
|
||||
// We only get here if `forwardingTargetForSelector:` returns nil.
|
||||
// In that case, our weak target has been reclaimed. Return a dummy method signature to keep `doesNotRecognizeSelector:` from firing.
|
||||
// We'll emulate the Obj-c messaging nil behavior by setting the return value to nil in `forwardInvocation:`, but we'll assume that the return value is `sizeof(void *)`.
|
||||
// Other libraries handle this situation by making use of a global method signature cache, but that seems heavier than necessary and has issues as well.
|
||||
// See https://www.mikeash.com/pyblog/friday-qa-2010-02-26-futures.html and https://github.com/steipete/PSTDelegateProxy/issues/1 for examples of using a method signature cache.
|
||||
return [NSObject instanceMethodSignatureForSelector:@selector(init)];
|
||||
}
|
||||
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,36 @@
|
||||
//
|
||||
// FLAnimatedImageView.h
|
||||
// Flipboard
|
||||
//
|
||||
// Created by Raphael Schaad on 7/8/13.
|
||||
// Copyright (c) 2013-2015 Flipboard. All rights reserved.
|
||||
//
|
||||
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
@class FLAnimatedImage;
|
||||
@protocol FLAnimatedImageViewDebugDelegate;
|
||||
|
||||
|
||||
//
|
||||
// An `FLAnimatedImageView` can take an `FLAnimatedImage` and plays it automatically when in view hierarchy and stops when removed.
|
||||
// The animation can also be controlled with the `UIImageView` methods `-start/stop/isAnimating`.
|
||||
// It is a fully compatible `UIImageView` subclass and can be used as a drop-in component to work with existing code paths expecting to display a `UIImage`.
|
||||
// Under the hood it uses a `CADisplayLink` for playback, which can be inspected with `currentFrame` & `currentFrameIndex`.
|
||||
//
|
||||
@interface FLAnimatedImageView : UIImageView
|
||||
|
||||
// Setting `[UIImageView.image]` to a non-`nil` value clears out existing `animatedImage`.
|
||||
// And vice versa, setting `animatedImage` will initially populate the `[UIImageView.image]` to its `posterImage` and then start animating and hold `currentFrame`.
|
||||
@property (nonatomic, strong) FLAnimatedImage *animatedImage;
|
||||
@property (nonatomic, copy) void(^loopCompletionBlock)(NSUInteger loopCountRemaining);
|
||||
|
||||
@property (nonatomic, strong, readonly) UIImage *currentFrame;
|
||||
@property (nonatomic, assign, readonly) NSUInteger currentFrameIndex;
|
||||
|
||||
// The animation runloop mode. Enables playback during scrolling by allowing timer events (i.e. animation) with NSRunLoopCommonModes.
|
||||
// To keep scrolling smooth on single-core devices such as iPhone 3GS/4 and iPod Touch 4th gen, the default run loop mode is NSDefaultRunLoopMode. Otherwise, the default is NSDefaultRunLoopMode.
|
||||
@property (nonatomic, copy) NSString *runLoopMode;
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,442 @@
|
||||
//
|
||||
// FLAnimatedImageView.h
|
||||
// Flipboard
|
||||
//
|
||||
// Created by Raphael Schaad on 7/8/13.
|
||||
// Copyright (c) 2013-2015 Flipboard. All rights reserved.
|
||||
//
|
||||
|
||||
|
||||
#import "FLAnimatedImageView.h"
|
||||
#import "FLAnimatedImage.h"
|
||||
#import <QuartzCore/QuartzCore.h>
|
||||
|
||||
|
||||
#if defined(DEBUG) && DEBUG
|
||||
@protocol FLAnimatedImageViewDebugDelegate <NSObject>
|
||||
@optional
|
||||
- (void)debug_animatedImageView:(FLAnimatedImageView *)animatedImageView waitingForFrame:(NSUInteger)index duration:(NSTimeInterval)duration;
|
||||
@end
|
||||
#endif
|
||||
|
||||
|
||||
@interface FLAnimatedImageView ()
|
||||
|
||||
// Override of public `readonly` properties as private `readwrite`
|
||||
@property (nonatomic, strong, readwrite) UIImage *currentFrame;
|
||||
@property (nonatomic, assign, readwrite) NSUInteger currentFrameIndex;
|
||||
|
||||
@property (nonatomic, assign) NSUInteger loopCountdown;
|
||||
@property (nonatomic, assign) NSTimeInterval accumulator;
|
||||
@property (nonatomic, strong) CADisplayLink *displayLink;
|
||||
|
||||
@property (nonatomic, assign) BOOL shouldAnimate; // Before checking this value, call `-updateShouldAnimate` whenever the animated image or visibility (window, superview, hidden, alpha) has changed.
|
||||
@property (nonatomic, assign) BOOL needsDisplayWhenImageBecomesAvailable;
|
||||
|
||||
#if defined(DEBUG) && DEBUG
|
||||
@property (nonatomic, weak) id<FLAnimatedImageViewDebugDelegate> debug_delegate;
|
||||
#endif
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation FLAnimatedImageView
|
||||
@synthesize runLoopMode = _runLoopMode;
|
||||
|
||||
#pragma mark - Initializers
|
||||
|
||||
// -initWithImage: isn't documented as a designated initializer of UIImageView, but it actually seems to be.
|
||||
// Using -initWithImage: doesn't call any of the other designated initializers.
|
||||
- (instancetype)initWithImage:(UIImage *)image
|
||||
{
|
||||
self = [super initWithImage:image];
|
||||
if (self) {
|
||||
[self commonInit];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
// -initWithImage:highlightedImage: also isn't documented as a designated initializer of UIImageView, but it doesn't call any other designated initializers.
|
||||
- (instancetype)initWithImage:(UIImage *)image highlightedImage:(UIImage *)highlightedImage
|
||||
{
|
||||
self = [super initWithImage:image highlightedImage:highlightedImage];
|
||||
if (self) {
|
||||
[self commonInit];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (instancetype)initWithFrame:(CGRect)frame
|
||||
{
|
||||
self = [super initWithFrame:frame];
|
||||
if (self) {
|
||||
[self commonInit];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (instancetype)initWithCoder:(NSCoder *)aDecoder
|
||||
{
|
||||
self = [super initWithCoder:aDecoder];
|
||||
if (self) {
|
||||
[self commonInit];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)commonInit
|
||||
{
|
||||
self.runLoopMode = [[self class] defaultRunLoopMode];
|
||||
|
||||
if (@available(iOS 11.0, *)) {
|
||||
self.accessibilityIgnoresInvertColors = YES;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#pragma mark - Accessors
|
||||
#pragma mark Public
|
||||
|
||||
- (void)setAnimatedImage:(FLAnimatedImage *)animatedImage
|
||||
{
|
||||
if (![_animatedImage isEqual:animatedImage]) {
|
||||
if (animatedImage) {
|
||||
// Clear out the image.
|
||||
super.image = nil;
|
||||
// Ensure disabled highlighting; it's not supported (see `-setHighlighted:`).
|
||||
super.highlighted = NO;
|
||||
// UIImageView seems to bypass some accessors when calculating its intrinsic content size, so this ensures its intrinsic content size comes from the animated image.
|
||||
[self invalidateIntrinsicContentSize];
|
||||
} else {
|
||||
// Stop animating before the animated image gets cleared out.
|
||||
[self stopAnimating];
|
||||
}
|
||||
|
||||
_animatedImage = animatedImage;
|
||||
|
||||
self.currentFrame = animatedImage.posterImage;
|
||||
self.currentFrameIndex = 0;
|
||||
if (animatedImage.loopCount > 0) {
|
||||
self.loopCountdown = animatedImage.loopCount;
|
||||
} else {
|
||||
self.loopCountdown = NSUIntegerMax;
|
||||
}
|
||||
self.accumulator = 0.0;
|
||||
|
||||
// Start animating after the new animated image has been set.
|
||||
[self updateShouldAnimate];
|
||||
if (self.shouldAnimate) {
|
||||
[self startAnimating];
|
||||
}
|
||||
|
||||
[self.layer setNeedsDisplay];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#pragma mark - Life Cycle
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
// Removes the display link from all run loop modes.
|
||||
[_displayLink invalidate];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark - UIView Method Overrides
|
||||
#pragma mark Observing View-Related Changes
|
||||
|
||||
- (void)didMoveToSuperview
|
||||
{
|
||||
[super didMoveToSuperview];
|
||||
|
||||
[self updateShouldAnimate];
|
||||
if (self.shouldAnimate) {
|
||||
[self startAnimating];
|
||||
} else {
|
||||
[self stopAnimating];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (void)didMoveToWindow
|
||||
{
|
||||
[super didMoveToWindow];
|
||||
|
||||
[self updateShouldAnimate];
|
||||
if (self.shouldAnimate) {
|
||||
[self startAnimating];
|
||||
} else {
|
||||
[self stopAnimating];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setAlpha:(CGFloat)alpha
|
||||
{
|
||||
[super setAlpha:alpha];
|
||||
|
||||
[self updateShouldAnimate];
|
||||
if (self.shouldAnimate) {
|
||||
[self startAnimating];
|
||||
} else {
|
||||
[self stopAnimating];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setHidden:(BOOL)hidden
|
||||
{
|
||||
[super setHidden:hidden];
|
||||
|
||||
[self updateShouldAnimate];
|
||||
if (self.shouldAnimate) {
|
||||
[self startAnimating];
|
||||
} else {
|
||||
[self stopAnimating];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#pragma mark Auto Layout
|
||||
|
||||
- (CGSize)intrinsicContentSize
|
||||
{
|
||||
// Default to let UIImageView handle the sizing of its image, and anything else it might consider.
|
||||
CGSize intrinsicContentSize = [super intrinsicContentSize];
|
||||
|
||||
// If we have have an animated image, use its image size.
|
||||
// UIImageView's intrinsic content size seems to be the size of its image. The obvious approach, simply calling `-invalidateIntrinsicContentSize` when setting an animated image, results in UIImageView steadfastly returning `{UIViewNoIntrinsicMetric, UIViewNoIntrinsicMetric}` for its intrinsicContentSize.
|
||||
// (Perhaps UIImageView bypasses its `-image` getter in its implementation of `-intrinsicContentSize`, as `-image` is not called after calling `-invalidateIntrinsicContentSize`.)
|
||||
if (self.animatedImage) {
|
||||
intrinsicContentSize = self.image.size;
|
||||
}
|
||||
|
||||
return intrinsicContentSize;
|
||||
}
|
||||
|
||||
#pragma mark Smart Invert Colors
|
||||
|
||||
#pragma mark - UIImageView Method Overrides
|
||||
#pragma mark Image Data
|
||||
|
||||
- (UIImage *)image
|
||||
{
|
||||
UIImage *image = nil;
|
||||
if (self.animatedImage) {
|
||||
// Initially set to the poster image.
|
||||
image = self.currentFrame;
|
||||
} else {
|
||||
image = super.image;
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
|
||||
- (void)setImage:(UIImage *)image
|
||||
{
|
||||
if (image) {
|
||||
// Clear out the animated image and implicitly pause animation playback.
|
||||
self.animatedImage = nil;
|
||||
}
|
||||
|
||||
super.image = image;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark Animating Images
|
||||
|
||||
- (NSTimeInterval)frameDelayGreatestCommonDivisor
|
||||
{
|
||||
// Presision is set to half of the `kFLAnimatedImageDelayTimeIntervalMinimum` in order to minimize frame dropping.
|
||||
const NSTimeInterval kGreatestCommonDivisorPrecision = 2.0 / kFLAnimatedImageDelayTimeIntervalMinimum;
|
||||
|
||||
NSArray *delays = self.animatedImage.delayTimesForIndexes.allValues;
|
||||
|
||||
// Scales the frame delays by `kGreatestCommonDivisorPrecision`
|
||||
// then converts it to an UInteger for in order to calculate the GCD.
|
||||
NSUInteger scaledGCD = lrint([delays.firstObject floatValue] * kGreatestCommonDivisorPrecision);
|
||||
for (NSNumber *value in delays) {
|
||||
scaledGCD = gcd(lrint([value floatValue] * kGreatestCommonDivisorPrecision), scaledGCD);
|
||||
}
|
||||
|
||||
// Reverse to scale to get the value back into seconds.
|
||||
return scaledGCD / kGreatestCommonDivisorPrecision;
|
||||
}
|
||||
|
||||
|
||||
static NSUInteger gcd(NSUInteger a, NSUInteger b)
|
||||
{
|
||||
// http://en.wikipedia.org/wiki/Greatest_common_divisor
|
||||
if (a < b) {
|
||||
return gcd(b, a);
|
||||
} else if (a == b) {
|
||||
return b;
|
||||
}
|
||||
|
||||
while (true) {
|
||||
NSUInteger remainder = a % b;
|
||||
if (remainder == 0) {
|
||||
return b;
|
||||
}
|
||||
a = b;
|
||||
b = remainder;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (void)startAnimating
|
||||
{
|
||||
if (self.animatedImage) {
|
||||
// Lazily create the display link.
|
||||
if (!self.displayLink) {
|
||||
// It is important to note the use of a weak proxy here to avoid a retain cycle. `-displayLinkWithTarget:selector:`
|
||||
// will retain its target until it is invalidated. We use a weak proxy so that the image view will get deallocated
|
||||
// independent of the display link's lifetime. Upon image view deallocation, we invalidate the display
|
||||
// link which will lead to the deallocation of both the display link and the weak proxy.
|
||||
FLWeakProxy *weakProxy = [FLWeakProxy weakProxyForObject:self];
|
||||
self.displayLink = [CADisplayLink displayLinkWithTarget:weakProxy selector:@selector(displayDidRefresh:)];
|
||||
|
||||
[self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:self.runLoopMode];
|
||||
}
|
||||
|
||||
// Note: The display link's `.frameInterval` value of 1 (default) means getting callbacks at the refresh rate of the display (~60Hz).
|
||||
// Setting it to 2 divides the frame rate by 2 and hence calls back at every other display refresh.
|
||||
const NSTimeInterval kDisplayRefreshRate = 60.0; // 60Hz
|
||||
self.displayLink.frameInterval = MAX([self frameDelayGreatestCommonDivisor] * kDisplayRefreshRate, 1);
|
||||
|
||||
self.displayLink.paused = NO;
|
||||
} else {
|
||||
[super startAnimating];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setRunLoopMode:(NSString *)runLoopMode
|
||||
{
|
||||
if (![@[NSDefaultRunLoopMode, NSRunLoopCommonModes] containsObject:runLoopMode]) {
|
||||
NSAssert(NO, @"Invalid run loop mode: %@", runLoopMode);
|
||||
_runLoopMode = [[self class] defaultRunLoopMode];
|
||||
} else {
|
||||
_runLoopMode = runLoopMode;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)stopAnimating
|
||||
{
|
||||
if (self.animatedImage) {
|
||||
self.displayLink.paused = YES;
|
||||
} else {
|
||||
[super stopAnimating];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)isAnimating
|
||||
{
|
||||
BOOL isAnimating = NO;
|
||||
if (self.animatedImage) {
|
||||
isAnimating = self.displayLink && !self.displayLink.isPaused;
|
||||
} else {
|
||||
isAnimating = [super isAnimating];
|
||||
}
|
||||
return isAnimating;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark Highlighted Image Unsupport
|
||||
|
||||
- (void)setHighlighted:(BOOL)highlighted
|
||||
{
|
||||
// Highlighted image is unsupported for animated images, but implementing it breaks the image view when embedded in a UICollectionViewCell.
|
||||
if (!self.animatedImage) {
|
||||
[super setHighlighted:highlighted];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#pragma mark - Private Methods
|
||||
#pragma mark Animation
|
||||
|
||||
// Don't repeatedly check our window & superview in `-displayDidRefresh:` for performance reasons.
|
||||
// Just update our cached value whenever the animated image or visibility (window, superview, hidden, alpha) is changed.
|
||||
- (void)updateShouldAnimate
|
||||
{
|
||||
BOOL isVisible = self.window && self.superview && ![self isHidden] && self.alpha > 0.0;
|
||||
self.shouldAnimate = self.animatedImage && isVisible;
|
||||
}
|
||||
|
||||
|
||||
- (void)displayDidRefresh:(CADisplayLink *)displayLink
|
||||
{
|
||||
// If for some reason a wild call makes it through when we shouldn't be animating, bail.
|
||||
// Early return!
|
||||
if (!self.shouldAnimate) {
|
||||
FLLog(FLLogLevelWarn, @"Trying to animate image when we shouldn't: %@", self);
|
||||
return;
|
||||
}
|
||||
|
||||
NSNumber *delayTimeNumber = [self.animatedImage.delayTimesForIndexes objectForKey:@(self.currentFrameIndex)];
|
||||
// If we don't have a frame delay (e.g. corrupt frame), don't update the view but skip the playhead to the next frame (in else-block).
|
||||
if (delayTimeNumber) {
|
||||
NSTimeInterval delayTime = [delayTimeNumber floatValue];
|
||||
// If we have a nil image (e.g. waiting for frame), don't update the view nor playhead.
|
||||
UIImage *image = [self.animatedImage imageLazilyCachedAtIndex:self.currentFrameIndex];
|
||||
if (image) {
|
||||
FLLog(FLLogLevelVerbose, @"Showing frame %lu for animated image: %@", (unsigned long)self.currentFrameIndex, self.animatedImage);
|
||||
self.currentFrame = image;
|
||||
if (self.needsDisplayWhenImageBecomesAvailable) {
|
||||
[self.layer setNeedsDisplay];
|
||||
self.needsDisplayWhenImageBecomesAvailable = NO;
|
||||
}
|
||||
|
||||
self.accumulator += displayLink.duration * displayLink.frameInterval;
|
||||
|
||||
// While-loop first inspired by & good Karma to: https://github.com/ondalabs/OLImageView/blob/master/OLImageView.m
|
||||
while (self.accumulator >= delayTime) {
|
||||
self.accumulator -= delayTime;
|
||||
self.currentFrameIndex++;
|
||||
if (self.currentFrameIndex >= self.animatedImage.frameCount) {
|
||||
// If we've looped the number of times that this animated image describes, stop looping.
|
||||
self.loopCountdown--;
|
||||
if (self.loopCompletionBlock) {
|
||||
self.loopCompletionBlock(self.loopCountdown);
|
||||
}
|
||||
|
||||
if (self.loopCountdown == 0) {
|
||||
[self stopAnimating];
|
||||
return;
|
||||
}
|
||||
self.currentFrameIndex = 0;
|
||||
}
|
||||
// Calling `-setNeedsDisplay` will just paint the current frame, not the new frame that we may have moved to.
|
||||
// Instead, set `needsDisplayWhenImageBecomesAvailable` to `YES` -- this will paint the new image once loaded.
|
||||
self.needsDisplayWhenImageBecomesAvailable = YES;
|
||||
}
|
||||
} else {
|
||||
FLLog(FLLogLevelDebug, @"Waiting for frame %lu for animated image: %@", (unsigned long)self.currentFrameIndex, self.animatedImage);
|
||||
#if defined(DEBUG) && DEBUG
|
||||
if ([self.debug_delegate respondsToSelector:@selector(debug_animatedImageView:waitingForFrame:duration:)]) {
|
||||
[self.debug_delegate debug_animatedImageView:self waitingForFrame:self.currentFrameIndex duration:(NSTimeInterval)displayLink.duration * displayLink.frameInterval];
|
||||
}
|
||||
#endif
|
||||
}
|
||||
} else {
|
||||
self.currentFrameIndex++;
|
||||
}
|
||||
}
|
||||
|
||||
+ (NSString *)defaultRunLoopMode
|
||||
{
|
||||
// Key off `activeProcessorCount` (as opposed to `processorCount`) since the system could shut down cores in certain situations.
|
||||
return [NSProcessInfo processInfo].activeProcessorCount > 1 ? NSRunLoopCommonModes : NSDefaultRunLoopMode;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark - CALayerDelegate (Informal)
|
||||
#pragma mark Providing the Layer's Content
|
||||
|
||||
- (void)displayLayer:(CALayer *)layer
|
||||
{
|
||||
layer.contents = (__bridge id)self.image.CGImage;
|
||||
}
|
||||
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,26 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>en</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>$(CURRENT_PROJECT_VERSION)</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string></string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,17 @@
|
||||
//
|
||||
// PreviewCell.h
|
||||
// IOSMedaiPicker
|
||||
//
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
#import "FLAnimatedImage.h"
|
||||
@interface PreviewCell : UICollectionViewCell<UIScrollViewDelegate>
|
||||
@property(nonatomic ,strong)UIImageView *imgView;
|
||||
@property(nonatomic ,strong)UIScrollView *artScrollView;
|
||||
@property(nonatomic ,strong)UIImageView *playimgView;
|
||||
@property(nonatomic ,strong)FLAnimatedImageView *gifView;
|
||||
@property(nonatomic, copy) void (^cellTapClick)();
|
||||
-(void)setImg:(UIImage *)image;
|
||||
-(void)setGifImg:(NSData *)image;
|
||||
@end
|
||||
@@ -0,0 +1,158 @@
|
||||
//
|
||||
// PreviewCell.m
|
||||
// IOSMedaiPicker
|
||||
//
|
||||
//
|
||||
|
||||
#import "PreviewCell.h"
|
||||
#import "FLAnimatedImage.h"
|
||||
@implementation PreviewCell
|
||||
- (id)initWithFrame:(CGRect)frame
|
||||
{
|
||||
self = [super initWithFrame:frame];
|
||||
if (self) {
|
||||
CGFloat width=CGRectGetWidth(self.frame);
|
||||
CGFloat height=CGRectGetHeight(self.frame);
|
||||
self.artScrollView = [[UIScrollView alloc] init];
|
||||
self.artScrollView.frame = CGRectMake(0, 0, width, height);
|
||||
self.artScrollView.minimumZoomScale = 1;
|
||||
self.artScrollView.maximumZoomScale = 5.0;
|
||||
self.artScrollView.showsVerticalScrollIndicator = NO;
|
||||
self.artScrollView.showsHorizontalScrollIndicator = NO;
|
||||
UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
|
||||
[self.artScrollView addGestureRecognizer:tap1];
|
||||
UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)];
|
||||
tap2.numberOfTapsRequired = 2;
|
||||
[tap1 requireGestureRecognizerToFail:tap2];
|
||||
[self.artScrollView addGestureRecognizer:tap2];
|
||||
self.artScrollView.delegate = self;
|
||||
[self.contentView addSubview:self.artScrollView];
|
||||
|
||||
|
||||
self.playimgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, width, height)];
|
||||
self.playimgView.contentMode = UIViewContentModeCenter;
|
||||
[self.playimgView setImage:[UIImage imageNamed:@"dmcPicker.bundle/video_play.png"]];
|
||||
[self addSubview:self.playimgView];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
- (void)singleTap:(UITapGestureRecognizer *)tap {
|
||||
if (self.cellTapClick) {
|
||||
self.cellTapClick();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (void)doubleTap:(UITapGestureRecognizer *)tap {
|
||||
if (self.artScrollView.zoomScale > 1.0) {
|
||||
[self.artScrollView setZoomScale:1.0 animated:YES];
|
||||
} else {
|
||||
CGFloat width = self.frame.size.width;
|
||||
CGFloat height = self.frame.size.height;
|
||||
CGPoint touchPoint;
|
||||
|
||||
touchPoint = [tap locationInView:self.imgView];
|
||||
|
||||
CGFloat newZoomScale = self.artScrollView.maximumZoomScale;
|
||||
CGFloat xsize = width / newZoomScale;
|
||||
CGFloat ysize = height / newZoomScale;
|
||||
[self.artScrollView zoomToRect:CGRectMake(touchPoint.x - xsize/2, touchPoint.y - ysize/2, xsize, ysize) animated:YES];
|
||||
}
|
||||
}
|
||||
|
||||
-(void)setImg:(UIImage *)image
|
||||
{
|
||||
|
||||
//移除上一个artimage
|
||||
[self.imgView removeFromSuperview];
|
||||
[self.artScrollView setZoomScale:1.0 animated:NO];
|
||||
self.imgView = [[UIImageView alloc] init];
|
||||
self.imgView.contentMode = UIViewContentModeScaleAspectFit;
|
||||
self.imgView.frame = CGRectMake(0, 0,CGRectGetWidth(self.frame), CGRectGetHeight(self.frame));
|
||||
|
||||
// UIImageView *textimage=[[UIImageView alloc] initWithImage:image];
|
||||
// self.imgView.frame = [self setImageCGRect:textimage SCREENWIDTH:CGRectGetWidth(self.frame) SCREENHEIGHT:CGRectGetHeight(self.frame)];
|
||||
self.imgView.image = image;
|
||||
self.artScrollView.frame=self.imgView.frame;
|
||||
[self.artScrollView addSubview:self.imgView];
|
||||
|
||||
//设置scroll的contentsize的frame
|
||||
self.artScrollView.contentSize = self.imgView.frame.size;
|
||||
}
|
||||
|
||||
-(void)setGifImg:(NSData *)image
|
||||
{
|
||||
|
||||
[self.gifView removeFromSuperview];
|
||||
self.gifView = [[FLAnimatedImageView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame))];
|
||||
self.gifView.contentMode = UIViewContentModeScaleAspectFit;
|
||||
self.gifView.clipsToBounds = YES;
|
||||
[self addSubview:self.gifView];
|
||||
FLAnimatedImage *animatedImagegif = [FLAnimatedImage animatedImageWithGIFData: image];
|
||||
self.gifView.animatedImage = animatedImagegif;
|
||||
}
|
||||
|
||||
//这个方法的返回值决定了要缩放的内容(只能是UISCrollView的子控件)
|
||||
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
|
||||
{
|
||||
return self.imgView;
|
||||
}
|
||||
|
||||
|
||||
//控制缩放是在中心
|
||||
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
|
||||
{
|
||||
CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?
|
||||
|
||||
(scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
|
||||
|
||||
CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?
|
||||
|
||||
(scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
|
||||
|
||||
self.imgView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,
|
||||
|
||||
scrollView.contentSize.height * 0.5 + offsetY);
|
||||
}
|
||||
|
||||
//根据不同的比例设置尺寸
|
||||
-(CGRect) setImageCGRect:(UIImageView *)imageView SCREENWIDTH:(CGFloat)SCREENWIDTH SCREENHEIGHT:(CGFloat)SCREENHEIGHT
|
||||
{
|
||||
|
||||
CGFloat imageX = imageView.frame.size.width;
|
||||
|
||||
CGFloat imageY = imageView.frame.size.height;
|
||||
|
||||
CGRect imgfram;
|
||||
|
||||
CGFloat CGscale;
|
||||
|
||||
BOOL flx = (SCREENWIDTH / SCREENHEIGHT) > (imageX / imageY);
|
||||
|
||||
if(flx)
|
||||
{
|
||||
CGscale = SCREENHEIGHT / imageY;
|
||||
|
||||
imageX = imageX * CGscale;
|
||||
|
||||
imgfram = CGRectMake((SCREENWIDTH - imageX) / 2, 0, imageX, SCREENHEIGHT);
|
||||
|
||||
return imgfram;
|
||||
}
|
||||
else
|
||||
{
|
||||
CGscale = SCREENWIDTH / imageX;
|
||||
|
||||
imageY = imageY * CGscale;
|
||||
|
||||
imgfram = CGRectMake(0, (SCREENHEIGHT - imageY) / 2, SCREENWIDTH, imageY);
|
||||
|
||||
return imgfram;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,12 @@
|
||||
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
#import <Photos/Photos.h>
|
||||
@protocol DmcPreviewDelegate<NSObject>
|
||||
-(void) previewResultPicker:(NSMutableArray*) selectArray;
|
||||
-(void) previewDonePicker:(NSMutableArray*) selectArray;
|
||||
@end
|
||||
@interface PreviewViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate>
|
||||
@property (nonatomic, retain) NSMutableArray *preArray;
|
||||
@property (nonatomic,weak)id<DmcPreviewDelegate> _delegate;
|
||||
@end
|
||||
@@ -0,0 +1,281 @@
|
||||
|
||||
|
||||
#import "PreviewViewController.h"
|
||||
#import "PreviewCell.h"
|
||||
#import <AVFoundation/AVFoundation.h>
|
||||
#import <AVKit/AVKit.h>
|
||||
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
|
||||
#define SCREENH_HEIGHT [UIScreen mainScreen].bounds.size.height
|
||||
@interface PreviewViewController (){
|
||||
UICollectionView* collectionView;
|
||||
UIButton *selectButton;
|
||||
NSMutableArray *selectArray;
|
||||
UILabel * titleView;
|
||||
int nowIndex;
|
||||
UICollectionViewFlowLayout *flowLayout ;
|
||||
}
|
||||
@end
|
||||
|
||||
@implementation PreviewViewController
|
||||
|
||||
- (void)viewDidLoad {
|
||||
[super viewDidLoad];
|
||||
selectArray=[[NSMutableArray alloc]init];
|
||||
[selectArray addObjectsFromArray:_preArray];
|
||||
[self initView];
|
||||
}
|
||||
|
||||
-(void)setTitleStr:(PHAsset*)asset{
|
||||
if(!titleView){
|
||||
titleView=[[UILabel alloc]init];
|
||||
titleView.frame = CGRectMake(0, 0, 0, self.navigationController.navigationBar.frame.size.height);
|
||||
titleView.textAlignment=NSTextAlignmentCenter;
|
||||
titleView.numberOfLines=3;
|
||||
titleView.adjustsFontSizeToFitWidth = true;
|
||||
self.navigationItem.titleView=titleView;
|
||||
}
|
||||
|
||||
|
||||
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
|
||||
|
||||
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
|
||||
|
||||
NSString * day=[dateFormatter stringFromDate:asset.creationDate];
|
||||
[dateFormatter setDateFormat:@"HH:mm:ss"];
|
||||
NSString * time =[dateFormatter stringFromDate:asset.creationDate];
|
||||
//获取标题的字符串
|
||||
NSString * str=[NSString stringWithFormat:@"%@\n%@",day,time];
|
||||
//创建一个带有属性的字符串比如说颜色,字体等文字的属性
|
||||
NSMutableAttributedString * attrStr=[[NSMutableAttributedString alloc]initWithString:str];
|
||||
|
||||
[attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:[str rangeOfString:day]];
|
||||
|
||||
[attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:11] range:[str rangeOfString:time]];
|
||||
|
||||
titleView.attributedText=attrStr;
|
||||
|
||||
|
||||
}
|
||||
|
||||
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
|
||||
|
||||
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
|
||||
[coordinator animateAlongsideTransition:^(id _Nonnull context) {
|
||||
[collectionView.collectionViewLayout invalidateLayout];
|
||||
[UIView performWithoutAnimation:^{
|
||||
CGFloat w= [UIScreen mainScreen].bounds.size.width;
|
||||
CGFloat h= [UIScreen mainScreen].bounds.size.height;
|
||||
collectionView.frame=CGRectMake(0, 0,w, h);
|
||||
flowLayout.itemSize = CGSizeMake(w, h);
|
||||
[collectionView setCollectionViewLayout:flowLayout];
|
||||
PreviewCell *cell = (PreviewCell*)[collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:nowIndex inSection:0]];
|
||||
cell.frame=CGRectMake(0, 0,w, h);
|
||||
[cell.artScrollView setZoomScale:1.0 animated:NO];
|
||||
cell.artScrollView.frame=CGRectMake(0, 0,w, h);
|
||||
cell.imgView.frame=CGRectMake(0, 0,w, h);
|
||||
cell.gifView.frame=CGRectMake(0, 0,w, h);
|
||||
[collectionView setContentOffset:CGPointMake(nowIndex*w, 0)];
|
||||
[collectionView layoutIfNeeded];
|
||||
}];
|
||||
[UIView performWithoutAnimation:^{
|
||||
[collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:nowIndex inSection:0]]];
|
||||
}];
|
||||
} completion:^(id _Nonnull context) {
|
||||
|
||||
}];
|
||||
}
|
||||
|
||||
|
||||
|
||||
-(void)initView{
|
||||
[self setTitleStr:_preArray[0]];
|
||||
UIWindow *window=[UIApplication sharedApplication].keyWindow;
|
||||
|
||||
flowLayout= [[UICollectionViewFlowLayout alloc] init];
|
||||
flowLayout.itemSize = CGSizeMake(window.bounds.size.width, window.bounds.size.height);
|
||||
//定义每个UICollectionView 横向的间距
|
||||
flowLayout.minimumLineSpacing = 0;
|
||||
flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
|
||||
collectionView =[[UICollectionView alloc] initWithFrame:CGRectMake(0, 0,window.bounds.size.width, window.bounds.size.height) collectionViewLayout:flowLayout];
|
||||
collectionView.backgroundColor=[UIColor whiteColor];
|
||||
collectionView.dataSource = self;
|
||||
collectionView.delegate = self;
|
||||
collectionView.pagingEnabled = YES;
|
||||
collectionView.scrollsToTop = NO;
|
||||
collectionView.showsHorizontalScrollIndicator = NO;
|
||||
//collectionView.contentOffset = CGPointMake(0, 0);
|
||||
//collectionView.contentSize = CGSizeMake([_preArray count] * window.bounds.size.width,0);
|
||||
[collectionView registerClass:[PreviewCell class] forCellWithReuseIdentifier:@"cell"];
|
||||
[self.view addSubview: collectionView];
|
||||
self.automaticallyAdjustsScrollViewInsets = NO;
|
||||
// 创建使用自定义图片的UIBarButtonItem
|
||||
CGFloat toolH=[self.navigationController toolbar].bounds.size.height*0.65;
|
||||
selectButton= [[UIButton alloc] initWithFrame:CGRectMake(0, 0, toolH, toolH)];
|
||||
[selectButton.widthAnchor constraintEqualToConstant:toolH].active = YES;
|
||||
[selectButton.heightAnchor constraintEqualToConstant:toolH].active = YES;
|
||||
[selectButton setImage:[UIImage imageNamed:@"dmcPicker.bundle/select80.png"] forState:UIControlStateNormal];
|
||||
[selectButton addTarget:self action:@selector(setSelectView) forControlEvents:UIControlEventTouchUpInside];
|
||||
UIBarButtonItem * selectButtonItem =[[UIBarButtonItem alloc] initWithCustomView:selectButton];
|
||||
UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
|
||||
UIBarButtonItem* doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(done)];
|
||||
[self setToolbarItems:@[selectButtonItem,flexibleSpace,doneButton] animated:YES];
|
||||
}
|
||||
|
||||
#pragma mark collectionView代理方法
|
||||
//返回section个数
|
||||
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
//每个section的item个数
|
||||
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
|
||||
{
|
||||
return [_preArray count];
|
||||
}
|
||||
|
||||
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
|
||||
{
|
||||
__weak typeof(self) weakSelf = self;
|
||||
static NSString *identify = @"cell";
|
||||
PreviewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
|
||||
PHAsset *asset=_preArray[indexPath.item];//访问已释放的对象
|
||||
PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
|
||||
option.resizeMode = PHImageRequestOptionsResizeModeFast;
|
||||
NSString *fileName =[asset valueForKey:@"filename"];
|
||||
NSString * fileExtension = [fileName pathExtension];
|
||||
|
||||
if([@"GIF" caseInsensitiveCompare:fileExtension]){
|
||||
cell.gifView.hidden=YES;
|
||||
[[PHImageManager defaultManager] requestImageForAsset:asset targetSize:CGSizeMake(SCREEN_WIDTH*3 , SCREENH_HEIGHT*3) contentMode:PHImageContentModeAspectFill options:option resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
|
||||
[cell setImg:result];
|
||||
}];
|
||||
}else{
|
||||
cell.imgView.hidden=YES;
|
||||
[[PHImageManager defaultManager] requestImageDataForAsset:asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
|
||||
[cell setGifImg:imageData];
|
||||
}];
|
||||
}
|
||||
|
||||
cell.playimgView.hidden=asset.mediaType==PHAssetMediaTypeVideo?NO:YES;
|
||||
[cell setCellTapClick:^{
|
||||
asset.mediaType!=PHAssetMediaTypeVideo?[weakSelf barStatus]:[weakSelf playVideo:asset];
|
||||
}];
|
||||
return cell;
|
||||
}
|
||||
|
||||
-(Boolean) getOrientation
|
||||
{
|
||||
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
|
||||
if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) {
|
||||
return YES;
|
||||
}else if (orientation == UIInterfaceOrientationLandscapeRight || orientation == UIInterfaceOrientationLandscapeLeft){
|
||||
return NO;
|
||||
}
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
-(void)playVideo:(PHAsset *)asset
|
||||
{
|
||||
if(asset.mediaType!=PHAssetMediaTypeVideo){
|
||||
return;
|
||||
}
|
||||
[[PHImageManager defaultManager] requestPlayerItemForVideo:asset options:nil resultHandler:^(AVPlayerItem * _Nullable playerItem, NSDictionary * _Nullable info) {
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
AVPlayerViewController *playerViewController = [AVPlayerViewController new];
|
||||
playerViewController.player = [[AVPlayer alloc]initWithPlayerItem:playerItem];
|
||||
[self presentViewController:playerViewController animated:YES completion:nil];
|
||||
[playerViewController.player play];
|
||||
});
|
||||
|
||||
}];
|
||||
}
|
||||
|
||||
- ( void)scrollViewDidScroll:( UIScrollView *)scrollView
|
||||
{
|
||||
int lasetSeIndex=nowIndex;
|
||||
nowIndex =[self getNowIndex];
|
||||
if(lasetSeIndex!=nowIndex){
|
||||
[self setTitleStr:_preArray[nowIndex]];
|
||||
Boolean select=[self isSelect:_preArray[nowIndex]]<0?YES:NO;
|
||||
if(select){
|
||||
[selectButton setImage:[UIImage imageNamed:@"dmcPicker.bundle/check_box_default.png"] forState:UIControlStateNormal];
|
||||
}else{
|
||||
[selectButton setImage:[UIImage imageNamed:@"dmcPicker.bundle/select80.png"] forState:UIControlStateNormal];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
-(int)getNowIndex{
|
||||
// 将collectionView在控制器view的中心点转化成collectionView上的坐标
|
||||
CGPoint pInView = [self.view convertPoint:collectionView.center toView:collectionView];
|
||||
// 获取这一点的indexPath
|
||||
NSIndexPath *visiablePath = [collectionView indexPathForItemAtPoint:pInView];
|
||||
return visiablePath.item;
|
||||
}
|
||||
|
||||
-(void)barStatus{
|
||||
if([self.navigationController isNavigationBarHidden]){
|
||||
[self.navigationController setNavigationBarHidden:NO animated:NO];
|
||||
[self.navigationController setToolbarHidden:NO animated:NO];
|
||||
collectionView.backgroundColor=[UIColor whiteColor];
|
||||
|
||||
}else{
|
||||
// [self prefersStatusBarHidden];
|
||||
[self.navigationController setNavigationBarHidden:YES animated:NO];
|
||||
[self.navigationController setToolbarHidden:YES animated:NO];
|
||||
collectionView.backgroundColor=[UIColor blackColor];
|
||||
}
|
||||
}
|
||||
|
||||
-(void)setSelectView{
|
||||
Boolean select=[self isSelect:_preArray[nowIndex]]<0?NO:YES;
|
||||
if(select){
|
||||
[selectButton setImage:[UIImage imageNamed:@"dmcPicker.bundle/check_box_default.png"] forState:UIControlStateNormal];
|
||||
[selectArray removeObject:_preArray[nowIndex]];
|
||||
}else{
|
||||
[selectButton setImage:[UIImage imageNamed:@"dmcPicker.bundle/select80.png"] forState:UIControlStateNormal];
|
||||
[selectArray addObject:_preArray[nowIndex]];
|
||||
}
|
||||
}
|
||||
|
||||
-(NSInteger)isSelect:(PHAsset *)asset
|
||||
{
|
||||
int is=-1;
|
||||
if([selectArray count]<=0){
|
||||
return is;
|
||||
}
|
||||
for(NSInteger i=0;i<[selectArray count];i++){
|
||||
PHAsset *now=selectArray[i];
|
||||
if ([asset.localIdentifier isEqualToString:now.localIdentifier]) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return is;
|
||||
}
|
||||
|
||||
-(void)done {
|
||||
|
||||
[self._delegate previewDonePicker:selectArray];
|
||||
|
||||
[self.navigationController popViewControllerAnimated:true];
|
||||
}
|
||||
|
||||
- (BOOL)prefersStatusBarHidden {
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)viewWillDisappear:(BOOL)animated {
|
||||
[self._delegate previewResultPicker:selectArray];
|
||||
[self.navigationController setToolbarHidden:NO];
|
||||
}
|
||||
|
||||
|
||||
- (void)didReceiveMemoryWarning {
|
||||
[super didReceiveMemoryWarning];
|
||||
}
|
||||
@end
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 630 B |
Binary file not shown.
|
After Width: | Height: | Size: 2.8 KiB |
@@ -1,9 +1,10 @@
|
||||
"Cancel"="Cancel";
|
||||
"Done"="Done";
|
||||
"all"="all";
|
||||
"All"="All photos";
|
||||
"Video"="Video";
|
||||
"maxSelectAlert"="Has reached the maximum number of choices";
|
||||
"ok"="OK";
|
||||
"Unable to access album" = "Unable to access album";
|
||||
"Please allow to access your album" = "Please allow to access your album in \"Settings -> Privacy -> Album\"";
|
||||
"Setting" = "Setting";
|
||||
"Preview" = "Preview";
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"Cancel"="取消";
|
||||
"Done"="完成";
|
||||
"All"="所有";
|
||||
"All"="所有照片";
|
||||
"Video"="视频";
|
||||
"maxSelectAlert"="已达到选择数量上限";
|
||||
"ok"="好";
|
||||
"Unable to access album" = "无法访问相册";
|
||||
"Please allow to access your album" = "请在设置-隐私-相册中允许访问相册";
|
||||
"Setting" = "设置";
|
||||
"Preview" = "预览";
|
||||
|
||||
Reference in New Issue
Block a user