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
}
}