Last active
August 2, 2019 15:10
-
-
Save taji-taji/ee9836605504344a978730d96d8ef07b to your computer and use it in GitHub Desktop.
【Swift】切り抜かずにUIImageを回転させる ref: https://qiita.com/taji-taji/items/4f01273b303edec45d46
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| } | |
| } | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| } | |
| } | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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