旋转UIImage我使用了一个从互联网上下载的扩展。在那里,旋转工作,但有一些有线行为。旋转UIImage问题 - IOS/Swift
这是扩展码
import UIKit
extension UIImage {
public func imageRotatedByDegrees(degrees: CGFloat, flip: Bool) -> UIImage {
let radiansToDegrees: (CGFloat) -> CGFloat = {
return $0 * (180.0/CGFloat(M_PI));
}
let degreesToRadians: (CGFloat) -> CGFloat = {
return $0/180.0 * CGFloat(M_PI);
}
// calculate the size of the rotated view's containing box for our drawing space
let rotatedViewBox = UIView(frame: CGRect(origin: CGPointZero, size: size));
let t = CGAffineTransformMakeRotation(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.0, rotatedSize.height/2.0);
// Rotate the image context
CGContextRotateCTM(bitmap, degreesToRadians(degrees));
// Now, draw the rotated/scaled image into the context
var yFlip: CGFloat;
if(flip){
yFlip = CGFloat(-1.0);
} else {
yFlip = CGFloat(1.0);
}
CGContextScaleCTM(bitmap, yFlip, -1.0);
CGContextDrawImage(bitmap, CGRectMake(-size.width/2, -size.height/2, size.width, size.height), CGImage);
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
}
这是我如何调用扩展方法并设置返回图像输出到图像视图。图像视图的“contentMode”属性设置为“缩放以填充”
currentPagePreviewImageVew.image = currentPagePreviewImageVew.image!.imageRotatedByDegrees(90, flip: false);
这是它按下旋转按钮之前的外观
这是一次按下旋转按钮后(见图片不旋转,但它的规模已经改变)
这是当图像R浮选是90度。(图像旋转这里之后,但如可以看到其它视图得到拉伸时图像是在0和180度如在上述屏幕(2))
可以将某些一个请告诉我我的代码有什么问题,如果有更好的解决方案,请告诉我。任何帮助将不胜感激。
编辑:拉伸视图是由于约束问题。我通过将高度约束放置在imageview上方的工具栏来解决问题。但仍然无法找到第一次的答案。
我有一个问题,因为改变仿射变换矩阵对自动布局约束有影响,这可能是一个类似的问题 – Daniel
@simpleBob你做了什么工作来完成工作? – GMHSJ
我删除并再次在对象上设置约束 – Daniel