【发布时间】:2016-08-24 06:13:34
【问题描述】:
为了旋转 UIImage,我使用了从 Internet 下载的扩展程序。在那里,旋转工作正常,但有一些有线行为。
这是扩展代码
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' 属性设置为 'Scale to Fill'
currentPagePreviewImageVew.image = currentPagePreviewImageVew.image!.imageRotatedByDegrees(90, flip: false);
这是按下旋转按钮之前的样子
这是在按下旋转按钮一次之后。(看到图像没有旋转但它的大小已经改变)
这是当图像旋转 90 度时。(在图像旋转之后,但您可以看到其他视图在图像处于 0 度和 180 度时被拉伸,如上面的屏幕(2))
谁能告诉我我的代码有什么问题,如果有更好的解决方案,请告诉我。任何帮助将不胜感激。
已编辑: 拉伸视图是由于约束问题。我通过在图像视图上方的工具栏上设置高度约束来解决它。但仍然找不到第一次的答案。
【问题讨论】:
-
我遇到了一个问题,因为更改仿射变换矩阵会影响自动布局约束,这可能是一个类似的问题
-
@simpleBob 你做了什么来完成你的工作?
-
我在对象上删除并再次设置约束
-
@simpleBob 谢谢伙计。我会试试的。
-
@simpleBob 是的,这是一个约束问题。但仍然有第一次的事情。谢谢
标签: ios swift rotation uiimage swift-extensions