現(xiàn)象描述
圖片在相冊中的顯示方向是對的嫂用,但是從相冊中取出圖片然后顯示在UIImageView上時圖片發(fā)生了旋轉(zhuǎn)型凳;
使用下面的取圖片方法圖片會發(fā)生旋轉(zhuǎn)
用下面這段代碼取出圖片在放到UIImageView上就可能會發(fā)生旋轉(zhuǎn)
// 通過ALAsset獲取UIImage
- (UIImage *) imageFromALAsset:(ALAsset *)asset
{
if ([[asset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto])
{
ALAssetRepresentation *rep = [asset defaultRepresentation];
CGImageRef ref = [rep fullResolutionImage];
UIImage *img = [[UIImage alloc]initWithCGImage:ref ];
return img;
}
return nil;
}
// 通過assetURL獲取ALAsset
- (void)assetFromURL:(NSURL*)assetsUrl
{
ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];
[lib assetForURL:assetsUrl resultBlock:^(ALAsset *asset) {
// _OrientationIV是UIImageView的一個實例
_OrientationIV.image = [self imageFromALAsset:asset];
} failureBlock:^(NSError *error) {
}];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
NSURL *as = [info objectForKey:UIImagePickerControllerReferenceURL];
[self assetFromURL:as];
[picker dismissViewControllerAnimated:YES completion:nil];
}
但是同一張圖片用下面的代碼獲取就不會發(fā)生旋轉(zhuǎn)
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{ UIImage *img = [info objectForKey:UIImagePickerControllerOriginalImage];
_OrientationIV.image = img; // _OrientationIV是UIImageView的一個實例
[picker dismissViewControllerAnimated:YES completion:nil];
}
所以猜測發(fā)生旋轉(zhuǎn)的問題可能發(fā)生在通過ALAsset獲取UIImage這塊代碼中的下面這一行代碼
// 方法一
UIImage *img = [[UIImage alloc]initWithCGImage:ref ];
于是查看API文檔,發(fā)現(xiàn)還有一個通過CGImage生成UIImage的方法
// 方法二
- (instancetype)initWithCGImage:(CGImageRef)cgImage scale:(CGFloat)scale orientation:(UIImageOrientation)orientation
這個“方法二”比“方法一”多了一個scale
參數(shù)和一個orientation
參數(shù),這里要使用orientation
參數(shù)來解決問題嘱函;
恰好ALAssetRepresentation
中有一個獲取orientation
的方法甘畅,只要將orientation
做參數(shù)傳遞給“方法二”就可以解決圖片旋轉(zhuǎn)的問題,
這里有一個注意點."方法二"中參數(shù)的類型是
UIImageOrientation
類型往弓,而從ALAssetRepresentation
中獲取的orientation
是ALAssetOrientation
類型疏唾,所以在使用時要用下面的代碼做一下強(qiáng)轉(zhuǎn)
UIImageOrientation orientation = (UIImageOrientation)[rep orientation];
最終正確的代碼如下:
- (UIImage *) imageFromALAsset:(ALAsset *)asset
{
if ([[asset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto])
{
ALAssetRepresentation *rep = [asset defaultRepresentation];
CGImageRef ref = [rep fullResolutionImage];
// 解決圖片發(fā)生旋轉(zhuǎn)的問題
UIImageOrientation orientation = (UIImageOrientation)[rep orientation];
UIImage *img = [[UIImage alloc]initWithCGImage:ref scale:1.0 orientation:orientation];
return img;
}
return nil;
}