func degreesToRadians(degrees: CGFloat) -> CGFloat {
return degrees * CGFloat(M_PI) / 180
}
func imageRotatedByDegrees(degrees: CGFloat) -> UIImage {
// calculate the size of the rotated view's containing box for our drawing space
let rotatedViewBox = UIView(frame: CGRectMake(0,0,self.size.width, self.size.height))
let t = CGAffineTransformMakeRotation(self.degreesToRadians(degrees))
rotatedViewBox.transform = t
let rotatedSize = rotatedViewBox.frame.size
// Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize)
let bitmap = UIGraphicsGetCurrentContext()
// Move the origin to the middle of the image so we will rotate and scale around the center.
CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);
// Now, draw the rotated/scaled image into the context
CGContextScaleCTM(bitmap, 1.0, -1.0);
CGContextDrawImage(bitmap, CGRectMake(-self.size.width / 2, -self.size.height / 2, self.size.width, self.size.height), self.CGImage);
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
11 回答
Swift 4:
这是将图像旋转到任何程度的完整代码,只需将其添加到适当的文件,即在.m中,如下所示,您要使用图像处理
for .m
这是苹果公司的代码片段SquareCam示例 .
要调用上述方法,只需使用以下代码即可
这里 square 是一个
UIImage
和 rotationDegrees 是一个flote
ivar旋转图像度Swift 3和Swift 4使用.pi代替
例如:
只需将此代码添加到图像中即可 .
我在XCode 6.3 Swift 1.2中尝试了这个错误
你应该尝试这个强制类型转换修复:
Swift 3版本:
Swift 4 | Xcode 9 syntax (请注意,此代码将UIImageView顺时针旋转90度,而不是UIImage):
Swift 4+.
Note: angle is in radian
如果你想添加动画
Output:
这是iOSDev答案的Swift 2.2版本(在UIImage扩展中):
最好只使用位图 . 在我的情况下使用在reference.image中的UIImage,我在base64String转换了图像 . 没有CGAffineTransformMakeRotation而没有rotateViewBox.transform