调整大小后的图像周围有白色边框 [英] White Border around Resized Image

查看:195
本文介绍了调整大小后的图像周围有白色边框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码调整图像的大小。但是我一直在底部获得白色边框

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
    }

我尝试使用 floor 函数取整值。但是仍然是同样的问题。

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

推荐答案

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

如果要考虑屏幕比例,只需将除以(NSScreen.main?.backingScaleFactor ?? 1)计算ratioX和ratioY

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

这篇关于调整大小后的图像周围有白色边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆