【发布时间】:2018-01-28 04:20:17
【问题描述】:
我正在使用以下代码调整图像大小(保持纵横比)。当我尝试将大小为 2432X3648 像素的图像调整为 1800X2700 像素 输出图像原点发生偏移。
extension NSImage {
func resizeTo(width: CGFloat, height: CGFloat) -> NSImage {
let ratioX = width / size.width
let ratioY = height / size.height
var ratio = ratioX < ratioY ? ratioX : ratioY
let newHeight = size.height * ratio
let newWidth = size.width * ratio
let canvasSize = CGSize(width: newWidth, height: newHeight)
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
}
}
请查看调整大小的示例图像。我已经标记了图像。调整大小的代码在其他情况下似乎可以正常工作。请建议..
更新: @LeoDabus我已经使用了你的代码,它为输出大小1084X2086像素产生了类似的结果。我不得不稍微修改你的代码 - 只在一行上,因为它不会编译。编译器自动建议它。 NSGraphicsContext.current()?.imageInterpolation = .high
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()
NSGraphicsContext.current()?.imageInterpolation = .high
draw(in: NSRect(origin: CGPoint(x: (canvasSize.width - (size.width * ratio)) / 2, y: (canvasSize.height - (size.height * ratio)) / 2), size: NSSize(width: newWidth,height: newHeight)), from: NSRect(origin: .zero, size: size), operation: .copy, fraction: 1)
img.unlockFocus()
return img
}
【问题讨论】:
-
@LeoDabus 感谢您的回复。原始方法是什么?
-
@LeoDabus 'resizedTo' 方法似乎相同....由于评论中提到的空白问题,我想我已经改变了。
-
@LeoDabus 你看到更新了吗?
-
我投票结束这个问题作为离题,因为作者已经删除了太多的问题,以至于不清楚问题的意图。