前端之家收集整理的这篇文章主要介绍了
swift3.0 上传图片旋转问题,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
extension UIImage {
func rotate(aImage:UIImage) -> UIImage {
// 向上 直接返回
if aImage.imageOrientation == .up {
return aImage
}
// 向下M_PI 向左M_PI_2 向右-M_PI_2
var transform: CGAffineTransform = CGAffineTransform.identity
switch aImage.imageOrientation {
case .down,.downMirrored:
transform = transform.translatedBy(x: aImage.size.width,y: aImage.size.height)
transform = transform.rotated(by: CGFloat(M_PI))
case .left,.leftMirrored:
transform = transform.translatedBy(x: aImage.size.width,y: 0)
transform = transform.rotated(by: CGFloat(M_PI_2))
case .right,.rightMirrored:
transform = transform.translatedBy(x: 0,y: aImage.size.height)
transform = transform.rotated(by: CGFloat(-M_PI_2))
default:
break
}
switch aImage.imageOrientation {
case .upMirrored,y: 0)
transform = transform.scaledBy(x: -1,y: 1)
case .leftMirrored,.rightMirrored:
transform = transform.translatedBy(x: aImage.size.height,y: 1)
default:
break
}
//渲染
let ctx: CGContext = CGContext(data: nil,width: Int(aImage.size.width),height: Int(aImage.size.height),bitsPerComponent: aImage.cgImage!.bitsPerComponent,bytesPerRow: 0,space: aImage.cgImage!.colorSpace!,bitmapInfo: aImage.cgImage!.bitmapInfo.rawValue)!
ctx.concatenate(transform)
switch aImage.imageOrientation {
case .left,.leftMirrored,.right,.rightMirrored:
ctx.draw(aImage.cgImage!,in: CGRect(x: 0,y: 0,width: aImage.size.height,height: aImage.size.width))
default:
ctx.draw(aImage.cgImage!,width: aImage.size.width,height: aImage.size.height))
}
// 新的图片
let cgimg: CGImage = ctx.makeImage()!
let img: UIImage = UIImage(cgImage: cgimg)
return img
}
}