我编写了一个扩展,将CGImages呈现为一个大的复合图像。我的错误是,得到的图像是预期分辨率的两倍。这是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
}
}发布于 2020-07-31 23:52:57
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
上一个参数scale = 0.0
如果指定值为0.0,则缩放因子设置为设备主屏幕的缩放因子。
(来自文件)
意味着它被设置为CGFloat scale = [[UIScreen mainScreen] scale];
对于Retina显示器来说,缩放因子可以是3.0或2.0,一个点可以分别用9个像素或4个像素表示。
建议设置
UIGraphicsBeginImageContextWithOptions(size, false, 1.0);再检查一遍
https://stackoverflow.com/questions/63198855
复制相似问题