【问题标题】:White Space Around Resized Image调整大小的图像周围的空白
【发布时间】:2017-10-06 10:57:10
【问题描述】:

我正在尝试通过保留纵横比来调整图像大小。但是调整后的图像周围有这个空白区域。

extension NSImage {
func resizeTo(width: CGFloat, height: CGFloat) -> NSImage {
    let ratioX = width / size.width
    let ratioY = height / size.height
    let ratio = ratioX < ratioY ? ratioX : ratioY
    let newHeight = size.height * ratio
    let newWidth = size.width * ratio
    let canvasSize = CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height)))
    let img = NSImage(size: canvasSize)
    img.lockFocus()
    let context = NSGraphicsContext.current()
    context?.imageInterpolation = .high
    draw(in: NSRect(origin: .zero, size: NSSize(width: newWidth,height: newHeight)), from: NSRect(origin: .zero, size: size) , operation: .copy, fraction: 1)
    img.unlockFocus()
    return img
    }
}

我做错了什么?

【问题讨论】:

    标签: swift macos nsimage


    【解决方案1】:

    首先,您从ratioXratioY 中选择最小的比率,但后来您使用ratioX(大小为widthheight * ratioX)创建画布。我想说你需要使用newWidthnewHeight 创建画布。

    let canvasSize = CGSize(width: newWidth, height: newHeight)
    

    此外,请注意,此脚本将在两个方向上调整大小,即会增加小图像的大小。

    【讨论】:

    • 如果您的意思是改进代码以不增加图像大小,只需添加检查比率:if (ratio) &gt; 0 ratio = 1;
    • 所以我这样做就像var ratio = ratioX &lt; ratioY ? ratioX : ratioY if (ratio) &gt; 0 { ratio = 1 }
    • 这会导致一些问题。
    • 没有详细说明就忍不住了。