ios - 在 UICollectionView 中显示照片库图像

标签 ios objective-c uicollectionview alassetslibrary

我正在尝试通过 ALAssetsLibraryUICollectionView 中显示照片库中的图像,我的代码运行良好,但我遇到了一些问题。

  1. 缩略图的质量很差。
  2. 如何安排收藏 View 按顺序显示 100 张最近的照片 来自

从新到旧。

这是我的代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    // collect the photos
    NSMutableArray *collector = [[NSMutableArray alloc] initWithCapacity:0];
    ALAssetsLibrary *al = [ViewController defaultAssetsLibrary];
    [al enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
                      usingBlock:^(ALAssetsGroup *group, BOOL *stop)
     {
         [group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
          {
              if (asset) {
                  [collector addObject:asset];
              }
          }];

         self.photos = collector;
     }
                    failureBlock:^(NSError *error) { NSLog(@"error");}];


}



-(void)setPhotos:(NSArray *)photos {
    if (_photos != photos) {
        _photos = photos;
        [_collectionView reloadData];
    }
}


+ (ALAssetsLibrary *)defaultAssetsLibrary {
    static dispatch_once_t pred = 0;
    static ALAssetsLibrary *library = nil;
    dispatch_once(&pred, ^{
        library = [[ALAssetsLibrary alloc] init];
    });
    return library;
}



- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
       return _photos.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"Cell";

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

    UIImageView *collectionImageView = (UIImageView *)[cell viewWithTag:100];
    ALAsset *asset = [self.photos objectAtIndex:indexPath.row];


    UIImage* img = [UIImage imageWithCGImage:asset.thumbnail];
    img = [UIImage imageWithCGImage:img.CGImage scale:2.0 orientation:UIImageOrientationUp];

    [collectionImageView setImage:img];


    return cell;
}

最佳答案

使用以下代码对照片进行排序。

self.photos = [collector sortedArrayUsingComparator:^NSComparisonResult(ALAsset *first, ALAsset *second) {

   NSDate * date1 = [first valueForProperty:ALAssetPropertyDate];
    NSDate * date2 = [second valueForProperty:ALAssetPropertyDate];

    return [date1 compare:date2];
}];

关于ios - 在 UICollectionView 中显示照片库图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34417334/

相关文章:

ios - 如何显示一个屏幕 3 秒,然后切换到下一个屏幕?

ios - "Linker command failed with exit code 1 (use -v to see invocation)?"如何解决

swift - 事件指示器不会完成操作

objective-c - 我该如何解决 'Semantic Issue'

ios - UICollectionViewCell 的标签宽度错误

ios - 删除 UICollectionView 中的特定项目

iOS 核心数据错误 - 对多关系的值类型 Not Acceptable

ios - 如何在 Swift 中将 AnyObject 类型转换为 Int

ios - Objective-C - 读取 JSON key 时的问题

objective-c - 如何拆分一串单词并添加到数组中 - Objective C