使用UIGraphicsImageRenderer旋转图像?

问题描述 投票:1回答:2

UIGraphicsImageRenderer是在iOS 10中新引入的。我想知道是否有可能用它旋转UIImage(任何自定义角度)。我知道有classic wayCGContextRotateCTM

swift uikit ios10 image-rendering
2个回答
3
投票

您可以设置UIGraphicsImageRenderer来创建一个图像,并通过该调用UIGraphicsGetCurrentContext()并旋转上下文

    let renderer = UIGraphicsImageRenderer(size:sizeOfImage )
    let image = renderer.image(actions: { _ in
        let context = UIGraphicsGetCurrentContext()

        context?.translateBy(x: orgin.x, y: orgin.y)
        context?.rotate(by: angle)
        context?.draw(image.cgImage!, in: CGRect(origin: CGPoint(x: -orgin.x,y: -orgin.y), size: size))
    }
return image

1
投票

通过文档,也由于缺乏对这个问题的回复,我认为新的UIGraphicsImageRenderer是不可能的。以下是我在一天结束时解决的问题:

func changeImageRotation(forImage image:UIImage, rotation alpha:CGFloat) -> UIImage{

    var newSize:CGSize{
        let a = image.size.width
        let b = image.size.height

        let width = abs(cos(alpha)) * a + abs(sin(alpha)) * b
        let height = abs(cos(alpha)) * b + abs(sin(alpha)) * a

        return CGSize(width: width, height: height)
    }

    let size = newSize
    let orgin = CGPoint(x: size.width/2, y: size.height/2)

    UIGraphicsBeginImageContext(size)
    let context = UIGraphicsGetCurrentContext()

    context?.translateBy(x: orgin.x, y: orgin.y)
    context?.rotate(by: alpha)
    context?.draw(image.cgImage!, in: CGRect(origin: CGPoint(x: -orgin.x,y: -orgin.y), size: size))

    let newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage!
}

New Sizecor响应绘制旋转图像所需的矩形区域,而不改变其整体大小。然后旋转图像并在中心绘制。有关更多信息,请参阅此post

© www.soinside.com 2019 - 2024. All rights reserved.