extension NSImage {
    
    func resize(_ to: CGSize, isPixels: Bool = false) -> NSImage {
        
        var toSize = to
        let screenScale: CGFloat = NSScreen.main?.backingScaleFactor ?? 1.0

        if isPixels {
            
            toSize.width = to.width / screenScale
            toSize.height = to.height / screenScale
        }
    
        let toRect = NSRect(x: 0, y: 0, width: toSize.width, height: toSize.height)
        let fromRect =  NSRect(x: 0, y: 0, width: size.width, height: size.height)
        
        let newImage = NSImage(size: toRect.size)
        newImage.lockFocus()
        draw(in: toRect, from: fromRect, operation: NSCompositingOperation.copy, fraction: 1.0)
        newImage.unlockFocus()
    
        return newImage
    }
}

使用

let myImage = NSImage(named: "imageName")!
        
/// 调整到指定point(点)
let newSize = CGSize(width: 200, height: 100)
let newImage1 = myImage.resize(newSize)
        
/// 调整到指定Pixels(像素)
let newPixels = CGSize(width: 400, height: 200)
let newImage2 = myImage.resize(newPixels, isPixels: true)

本文由 Harvey 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论