使用 UIImagePicker 调用手机相机拍照或者图库中的照片,UIImageView中显示图片旋转90°或者180°.因为爱疯拍照的照片EXIF 记录含有方向信息(8个方向 imageOrientation).默认的照片方向是横向, Home 键在右侧
EXIF 位置值
使用函数 cell.imageView.image = fixOrientation(myPhoto)
func fixOrientation(aImage: UIImage) -> UIImage {
if (aImage.imageOrientation == .Up) {
return aImage
}
var transform = CGAffineTransformIdentity
switch (aImage.imageOrientation) {
case .Down, .DownMirrored:
transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI))
case .Left, .LeftMirrored:
transform = CGAffineTransformTranslate(transform, aImage.size.width, 0)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2))
case .Right, .RightMirrored:
transform = CGAffineTransformTranslate(transform, 0, aImage.size.height)
transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2))
default:
break
}
switch (aImage.imageOrientation) {
case .UpMirrored, .DownMirrored:
transform = CGAffineTransformTranslate(transform, aImage.size.width, 0)
transform = CGAffineTransformScale(transform, -1, 1)
case .LeftMirrored, .RightMirrored:
transform = CGAffineTransformTranslate(transform, aImage.size.height, 0)
transform = CGAffineTransformScale(transform, -1, 1)
default:
break
}
let ctx = CGBitmapContextCreate(nil, Int(aImage.size.width), Int(aImage.size.height),
CGImageGetBitsPerComponent(aImage.CGImage), 0,
CGImageGetColorSpace(aImage.CGImage),
CGImageGetBitmapInfo(aImage.CGImage))
CGContextConcatCTM(ctx, transform)
switch (aImage.imageOrientation) {
case .Left, .LeftMirrored, .Right, .RightMirrored:
CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage)
default:
CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage)
}
// And now we just create a new UIImage from the drawing context
let cgimg = CGBitmapContextCreateImage(ctx)
return UIImage(CGImage: cgimg!)!
}