首页 > 解决方案 > 如何在 UIGraphicsImageRenderer 中绘制对象之前对其进行旋转?

问题描述

    let renderer = UIGraphicsImageRenderer(size: CGSize(width: 500, height: 500))
    let image = renderer.image { context in
        let size = renderer.format.bounds.size
        UIColor.red.setFill()
        context.cgContext.fillEllipse(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        let x = 300 //center
        let y = 100 //center
        let w = 200
        let h = 60
        let r = 5.41 //radians
        UIColor.white.setFill()
        context.cgContext.fill(CGRect(x: x - w / 2, y: y - h / 2, width: w, height: h))
    }

结果是这样的:

在上下文中绘制之前,如何在矩形中间旋转我的白色矩形?

在此处输入图像描述

标签: iosswiftcore-graphics

解决方案


您可以使用以下 api 旋转上下文: https ://developer.apple.com/documentation/coregraphics/cgcontext/1456228-rotate

这就是您的示例的样子:

            // applied 5 rectangles to visualize the rotation origin.
            for i in 0...5 {
                let r: CGFloat = 0.1 * CGFloat(i) //radians
                context.cgContext.rotate(by: r)
                UIColor.white.setFill()
                context.cgContext.fill(CGRect(x: x - w / 2, y: y - h / 2, width: w, height: h))
            }

示例图像

请注意,旋转发生在上下文的原点周围。如果您想要一个不同的中心,您可能需要先申请翻译(translateBy(x:y:)- 有关详细信息,请参阅苹果文档)。


推荐阅读