调整大小图像周围的白色空间

时间:2017-10-06 10:57:11

标签: swift macos nsimage

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

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
    }
}

enter image description here

我做错了什么?

1 个答案:

答案 0 :(得分:1)

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

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

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

相关问题