【问题标题】:CGContext.draw(), CGContext.makeImage() giving me double intended resolutionCGContext.draw(), CGContext.makeImage() 给我双倍的预期分辨率
【发布时间】:2020-07-31 20:43:59
【问题描述】:

我编写了一个扩展来将 [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
    }
}

【问题讨论】:

  • 这是正确的,如果您打算在设备上显示它,您应该保持这样的状态

标签: swift cgcontext cgimage


【解决方案1】:

UIGraphicsBeginImageContextWithOptions(size, false, 0.0)

你的最后一个参数scale = 0.0

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

表示设置为CGFloat scale = [[UIScreen mainScreen] scale];

对于 Retina 显示器,比例因子可以是 3.0 或 2.0,一个点可以分别用九个或四个像素表示。

建议设置

UIGraphicsBeginImageContextWithOptions(size, false, 1.0);

然后再次检查

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-31
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 2018-09-27
    相关资源
    最近更新 更多