CIFilter自动旋转图像

时间:2015-03-11 23:06:15

标签: swift

CIFilter在使用后自动将图像旋转90度。

是否存在类似于objective-c修复的快速修复:

Image auto-rotates after using CIFilter

这是解决此问题的正确方法吗?

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,无法为swift寻找资源。我最终合并了2个示例并使用以下代码:

var angle = 0.0;
if (originImage.imageOrientation == UIImageOrientation.Right)
{
    angle = 90.0
}
else if (originImage.imageOrientation == UIImageOrientation.Left)
{
    angle = -90.0
}
else if (originImage.imageOrientation == UIImageOrientation.Down)
{
    angle = 180
}
else if (originImage.imageOrientation == UIImageOrientation.Up)
{
    angle = 0.0
}
filteredImage = filteredImage.imageRotatedByDegrees(CGFloat(angle), flip: false)

使用此扩展程序:

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
}
}

我猜这可以简化,但它对我有用。