IOS:根据图像大小更改UICollectionView Cell大小

时间:2013-08-15 09:16:48

标签: iphone ios uicollectionview

我想生成一个图库,而不改变图像的纵横比。图像尺寸不同。我正在使用UICollectionView并在单元格中定位UIImageView。我使用下面的代码来获取图像大小。但它总是返回0。

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

NSString* url = [selectedImages objectAtIndex:indexPath.row];

UIImageView *thumb;
ALAssetsLibraryAccessFailureBlock failureBlock  = ^(NSError *myError) {
    NSLog(@"failed loading asset");
};
ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset *myAsset) {
    [thumb setImage:[UIImage imageWithCGImage:[myAsset aspectRatioThumbnail]]];
};
ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];

[lib assetForURL:[NSURL URLWithString:url] resultBlock:resultBlock failureBlock:failureBlock];
NSLog(@"%f,%f",thumb.image.size.height,thumb.image.size.width);
return thumb.image.size;   
}

1 个答案:

答案 0 :(得分:0)

您的图片尺寸返回尺寸 0 总是因为UIImageview()获取^{} block中的图片且未在mainthread上执行, 所以,您必须在sizeForItemAtIndexPath此方法或

之前计算图像大小

你可以尝试这样,但我想这不是正确的方法,

ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset *myAsset) {
    [thumb setImage:[UIImage imageWithCGImage:[myAsset aspectRatioThumbnail]]];
return thumb.image.size;   

};