【发布时间】:2017-04-28 11:01:12
【问题描述】:
图片大小有问题。
最初我有任何尺寸的图像,可以裁剪成正方形
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
}
最终使用来自 answer 的 png 扩展名将图像保存到文件
通常一切正常...除了图像大小。 当我从某个大小开始并调整大小以假设为 100x100 时,我保存的图像具有双倍大小 (200x200)。
我的代码有什么问题?
【问题讨论】:
标签: swift macos resize nsimage