Swift CGContext.draw(),CGContext.makeImage()为我提供了两倍的预期分辨率

Swift CGContext.draw(),CGContext.makeImage()为我提供了两倍的预期分辨率,swift,cgcontext,cgimage,Swift,Cgcontext,Cgimage,我已经编写了一个扩展来将[CGImage]渲染成一个大的合成图像。我有一个缺陷,就是生成的图像的分辨率是预期分辨率的两倍。这是bytesPerRow的问题吗?还是别的什么 public extension Array where Element == CGImage { func render(cols: Int) -> CGImage? { guard count > 0 else { return nil } var maxWidth:

我已经编写了一个扩展来将[CGImage]渲染成一个大的合成图像。我有一个缺陷,就是生成的图像的分辨率是预期分辨率的两倍。这是bytesPerRow的问题吗?还是别的什么

public extension Array where Element == CGImage {
    func render(cols: Int) -> CGImage? {
        guard count > 0 else { return nil }

        var maxWidth: Int = 0
        var totalHeight: Int = 0

        var currentArrayIndex = 0

        while currentArrayIndex < count {
            var currentRowWidth = 0
            var maxRowHeight = 0
            for _ in 0..<cols {
                currentRowWidth += self[currentArrayIndex].width
                maxRowHeight = max(self[currentArrayIndex].height, maxRowHeight)
                currentArrayIndex += 1
            }
            maxWidth = max(maxWidth, currentRowWidth)
            totalHeight += maxRowHeight
        }

        let size = CGSize(width: maxWidth, height: totalHeight)
        UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
        guard let context = UIGraphicsGetCurrentContext() else { return nil }

        var x: Int = 0
        var y: Int = 0

        var rowMaxHeight = 0
        for image in self {

            context.saveGState()
            context.translateBy(x: 0, y: CGFloat(image.height))
            context.scaleBy(x: 1.0, y: -1.0)
            context.draw(image, in: CGRect(x: x, y: y, width: image.width, height: image.height))
            context.restoreGState()

            rowMaxHeight = max(image.height, rowMaxHeight)
            x += image.width
            if x >= Int(size.width) {
                x = 0
                y -= rowMaxHeight
            }
        }

        let cgImage = context.makeImage()
        UIGraphicsEndImageContext()
        return cgImage
    }

    private func max(_ one: Int, _ two: Int) -> Int {
        if one > two { return one }
        return two
    }
}

公共扩展数组,其中元素==CGImage{
func render(cols:Int)->CGImage{
保护计数>0其他{返回零}
变量maxWidth:Int=0
var totalHeight:Int=0
var currentArrayIndex=0
而currentArrayIndexInt{
如果一>二{返回一}
返回两个
}
}

UIGraphicsBeginImageContextWithOptions(大小,false,0.0)

您的最后一个参数
scale
=
0.0

如果指定的值为0.0,则比例因子将设置为设备主屏幕的比例因子
(来自文档)

这意味着它被设置为
CGFloat scale=[[UIScreen mainScreen]scale]

对于视网膜显示,比例因子可以是3.0或2.0,一个点可以分别由九个或四个像素表示

建议设立

UIGraphicsBeginImageContextWithOptions(size, false, 1.0);

然后再次检查

这是正确的,如果您想在设备上显示它,您应该像这样保存它