使用UIGraphicsImageRenderer旋转图像?

时间:2016-08-22 21:39:29

标签: swift uikit ios10 image-rendering

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

3 个答案:

答案 0 :(得分: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 :(得分: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 Size对应于绘制旋转图像而不改变其整体大小所需的矩形区域。然后旋转图像并在中心绘制。有关详细信息,请参阅此post

答案 2 :(得分:1)

建立在@ reza23的答案上。您无需调用UIGraphicsGetCurrentContext,就可以使用渲染器的上下文。

AppBar(
  flexibleSpace: Container(
    decoration: 
      BoxDecoration(
        image: DecorationImage(
          image: AssetImage(),
          fit: BoxFit.cover,
        ),
      ),
  ),
  backgroundColor: Colors.transparent,
  title: Text("App Bar"),
);