Skip to content

Instantly share code, notes, and snippets.

@taji-taji
Last active August 2, 2019 15:10
Show Gist options
  • Select an option

  • Save taji-taji/ee9836605504344a978730d96d8ef07b to your computer and use it in GitHub Desktop.

Select an option

Save taji-taji/ee9836605504344a978730d96d8ef07b to your computer and use it in GitHub Desktop.
【Swift】切り抜かずにUIImageを回転させる ref: https://qiita.com/taji-taji/items/4f01273b303edec45d46
extension UIImage {
func rotatedBy(degree: CGFloat) -> UIImage {
let radian = -degree * CGFloat.pi / 180
UIGraphicsBeginImageContext(self.size)
let context = UIGraphicsGetCurrentContext()!
context.translateBy(x: self.size.width / 2, y: self.size.height / 2)
context.scaleBy(x: 1.0, y: -1.0)
context.rotate(by: radian)
context.draw(self.cgImage!, in: CGRect(x: -(self.size.width / 2), y: -(self.size.height / 2), width: self.size.width, height: self.size.height))
let rotatedImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return rotatedImage
}
}
extension UIImage {
func rotatedBy(degree: CGFloat, isCropped: Bool = true) -> UIImage {
let radian = -degree * CGFloat.pi / 180
var rotatedRect = CGRect(origin: .zero, size: self.size)
if !isCropped {
rotatedRect = rotatedRect.applying(CGAffineTransform(rotationAngle: radian))
}
UIGraphicsBeginImageContext(rotatedRect.size)
let context = UIGraphicsGetCurrentContext()!
context.translateBy(x: rotatedRect.size.width / 2, y: rotatedRect.size.height / 2)
context.scaleBy(x: 1.0, y: -1.0)
context.rotate(by: radian)
context.draw(self.cgImage!, in: CGRect(x: -(self.size.width / 2), y: -(self.size.height / 2), width: self.size.width, height: self.size.height))
let rotatedImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return rotatedImage
}
}
CGRect(origin: .zero, size: self.size).applying(CGAffineTransform(rotationAngle: radian))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment