2017-10-06 90 views
0

我试图通过保持纵横比来调整图像大小。但是在调整大小的图像周围存在此空白区域。调整图像周围的白色空间

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

首先要从ratioXratioY采摘最小的比例,但后来创建使用ratioX(,大小widthheight * ratioX)的画布。我想说你需要使用newWidthnewHeight创建画布。

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

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

+0

好的..我该如何改进代码。请咨询。 – techno

+0

如果你的意思是改善代码不增加图像的大小,只需添加检查比例:'if(ratio)> 0 ratio = 1;' – Gedrox

+0

所以我这样做'var ratio = ratioX 0 { ratio = 1 } ' – techno