1 #import <AssetsLibrary/AssetsLibrary.h> 3 4 5 /** 6 * ALAssetsLibrary.h 代表资源库(所有的视频,照片) 7 ALAssetsGroup.h 代表资源库中的相册 8 ALAsset.h 代表相册中一个视频或者一张照片 9 ALAssetRepresentation.h 代表一个资源的描述,可以获取到原始图片 10 */ 11 12 @interface ViewController () 13 14 @property (weak, nonatomic) IBOutlet UICollectionView *collectionView; 15 16 @property (nonatomic,strong)NSMutableArray *array; 17 @end 18 19 @implementation ViewController{ 20 21 ALAssetsLibrary *library; 22 23 } 24 25 - (void)viewDidLoad { 26 [super viewDidLoad]; 27 28 //创建可变数组,存储资源文件 29 _array = [NSMutableArray array]; 30 31 //创建资源库,用于访问相册资源 32 library = [[ALAssetsLibrary alloc] init]; 33 34 //遍历资源库中所有的相册,有多少个相册,usingBlock会调用多少次 35 [library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) { 36 37 //如果存在相册,再遍历 38 if (group) { 39 40 //遍历相册中所有的资源(照片,视频) 41 [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) { 42 43 /* 44 资源的索引 45 if (index == 2) { 46 47 //停止遍历 48 *stop = YES; 49 } 50 */ 51 52 if (result) { 53 //将资源存储到数组中 54 [_array addObject:result]; 55 } 56 57 }]; 58 } 59 60 //刷新_collectionView reloadData; 61 [_collectionView reloadData]; 62 63 } failureBlock:^(NSError *error) { 64 65 NSLog(@"访问失败"); 66 }]; 67 68 } 69 70 #pragma mark -UICollectionViewDelegate 71 72 //行的个数 73 - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { 74 75 76 return _array.count; 77 78 } 79 80 //创建UICollectionViewCell 81 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { 82 83 //如果单元格是在故事版中画出来的,不需要注册,需要在单元格中指定标识符 84 UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath]; 85 86 //取得图片视图 87 UIImageView *imgView = (UIImageView *)[cell.contentView viewWithTag:1]; 88 89 //取出对应的资源数据 90 ALAsset *result =_array[indexPath.row]; 91 92 //获取到缩略图 93 CGImageRef cimg = [result thumbnail]; 94 95 //转换为UIImage 96 UIImage *img = [UIImage imageWithCGImage:cimg]; 97 98 //显示图片 99 imgView.image = img; 100 101 /** 102 * 获取到原始图片 103 ALAssetRepresentation *presentation = [result defaultRepresentation]; 104 105 CGImageRef resolutionImg = [presentation fullResolutionImage]; 106 */ 107 108 return cell; 109 110 } 111 112 //单元格大小 113 - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{ 114 115 return CGSizeMake(70, 70);
原文:http://www.cnblogs.com/mafeng/p/5830693.html