swift 图片调整大小和保存分辨率问题

swift image resize and save resolution issue

我的图片大小有问题。

最初我有任意尺寸的图像,我将其裁剪成正方形

func cropToSquare() -> NSImage? {
    let dimensions = [self.width, self.height]
    let lessValue = dimensions.min()
    let x = floor((self.width - lessValue!) / 2)
    let y = floor((self.height - lessValue!) / 2)
    let frame = NSMakeRect(x, y, lessValue!, lessValue!)
    guard let rep = self.bestRepresentation(for: frame, context: nil, hints: nil) else {
        return nil
    }
    let img = NSImage(size: NSSize(width: lessValue!, height: lessValue!))
    img.lockFocus()
    defer { img.unlockFocus() }
    if rep.draw(in: NSMakeRect(0, 0, lessValue!, lessValue!),
                from: frame,
                operation: NSCompositingOperation.copy,
                fraction: 1.0,
                respectFlipped: false,
                hints: [:]) {
        return img
    }
    return nil
}

接下来我调整图片大小

func copyWithSize(size: NSSize) -> NSImage? {
    let frame = NSMakeRect(0, 0, size.width, size.height)
    guard let rep = self.bestRepresentation(for: frame, context: nil, hints: nil) else {
        return nil
    }
    let img = NSImage(size: size)
    img.lockFocus()
    defer { img.unlockFocus() }
    if rep.draw(in: frame) {
        print(size, frame)
        return img
    }
    return nil
}

最终使用来自此

的 png 扩展名将图像保存到文件

通常一切正常...除了图像大小。 当我从某个尺寸开始并调整到 100x100 时,我保存的图像有双倍尺寸 (200x200)。

我的代码有什么问题?

图像正在 @2x 中绘制,因为您有 Mac 视网膜显示屏。

使用 lockFocus 创建一个新的图像显示在屏幕上,如果你想将它保存到文件中是不切实际的。

您可以使用以下方法获得比例因子:

NSScreen.main.backingScaleFactor

并相应地调整调整大小。

但最好的解决方案是创建一个 NSBitmapImageRep 并手动将其 size 设置为您想要的图像大小。