#import "ViewController.h"
#import <AssetsLibrary/AssetsLibrary.h> /**
* ALAssetsLibrary.h 代表资源库(所有的视频,照片)
ALAssetsGroup.h 代表资源库中的相册
ALAsset.h 代表相册中一个视频或者一张照片
ALAssetRepresentation.h 代表一个资源的描述,可以获取到原始图片
*/ @interface ViewController () @property (weak, nonatomic) IBOutlet UICollectionView *collectionView; @property (nonatomic,strong)NSMutableArray *array;
@end @implementation ViewController{ ALAssetsLibrary *library; } - (void)viewDidLoad {
[super viewDidLoad]; //创建可变数组,存储资源文件
_array = [NSMutableArray array]; //创建资源库,用于访问相册资源
library = [[ALAssetsLibrary alloc] init]; //遍历资源库中所有的相册,有多少个相册,usingBlock会调用多少次
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) { //如果存在相册,再遍历
if (group) { //遍历相册中所有的资源(照片,视频)
[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) { /*
资源的索引
if (index == 2) { //停止遍历
*stop = YES;
}
*/ if (result) {
//将资源存储到数组中
[_array addObject:result];
} }];
} //刷新_collectionView reloadData;
[_collectionView reloadData]; } failureBlock:^(NSError *error) { NSLog(@"访问失败");
}]; } #pragma mark -UICollectionViewDelegate //行的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return _array.count; } //创建UICollectionViewCell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { //如果单元格是在故事版中画出来的,不需要注册,需要在单元格中指定标识符
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath]; //取得图片视图
UIImageView *imgView = (UIImageView *)[cell.contentView viewWithTag:]; //取出对应的资源数据
ALAsset *result =_array[indexPath.row]; //获取到缩略图
CGImageRef cimg = [result thumbnail]; //转换为UIImage
UIImage *img = [UIImage imageWithCGImage:cimg]; //显示图片
imgView.image = img; /**
* 获取到原始图片
ALAssetRepresentation *presentation = [result defaultRepresentation]; CGImageRef resolutionImg = [presentation fullResolutionImage];
*/ return cell; } //单元格大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{ return CGSizeMake(, ); }
05-11 14:03