White Border around Resized Image

不打扰是莪最后的温柔 提交于 2020-04-30 09:07:11

问题


I'm using the following code to resize an image.But i keep getting a white border at the bottom

 func resize(withSize targetSize: NSSize) -> NSImage? {

        let size=NSSize(width: floor((targetSize.width/(NSScreen.main?.backingScaleFactor)!)), height:floor( (targetSize.height/(NSScreen.main?.backingScaleFactor)!)))

        let frame = NSRect(x: 0, y: 0, width: floor(size.width), height: floor(size.height))

        guard let representation = self.bestRepresentation(for: frame, context: nil,hints: nil) else {
            return nil
        }

        let image = NSImage(size: size, flipped: false, drawingHandler: { (_) -> Bool in
            return representation.draw(in: frame)
        })

        return image
    }

I have tried using floor function to round off the values.But still the same issue.


回答1:


extension NSImage {
    func resize(withSize targetSize: NSSize) -> NSImage? {
        let ratioX = targetSize.width / size.width / (NSScreen.main?.backingScaleFactor ?? 1)
        let ratioY = targetSize.height / size.height / (NSScreen.main?.backingScaleFactor ?? 1)
        let ratio = ratioX < ratioY ? ratioX : ratioY
        let canvasSize = NSSize(width: size.width * ratio, height: size.height * ratio)
        let frame = NSRect(origin: .zero, size: canvasSize)
        guard let representation = bestRepresentation(for: frame, context: nil, hints: nil)
        else { return nil }
        return NSImage(size: canvasSize, flipped: false) { _ in representation.draw(in: frame) }
    }
}

let image = NSImage(contentsOf: URL(string: "http://i.stack.imgur.com/Xs4RX.jpg")!)!
let resized = image.resize(withSize: .init(width: 400, height: 300))  // w 267 h 300

If you would like to take into account the screen scale just remove the division by (NSScreen.main?.backingScaleFactor ?? 1) from the method when calculating ratioX and ratioY



来源:https://stackoverflow.com/questions/61030581/white-border-around-resized-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!