How to resize NSImage?

前端 未结 10 1661
萌比男神i
萌比男神i 2020-12-02 21:21

I have an NSBitmapImageRep which is WxH size.

I create NSImage and call addRepresentation:. Then I n

10条回答
  •  一向
    一向 (楼主)
    2020-12-02 21:41

    Actually it is not necessary to modify any source image parameters like size. The following snippet is already in Swift, but I think you can infer the Objective-C version from it:

    func resized(to: CGSize) -> NSImage {
        let img = NSImage(size: to)
    
        img.lockFocus()
        defer {
            img.unlockFocus()
        }
    
        if let ctx = NSGraphicsContext.current {
            ctx.imageInterpolation = .high
            draw(in: NSRect(origin: .zero, size: to),
                 from: NSRect(origin: .zero, size: size),
                 operation: .copy,
                 fraction: 1)
        }
    
        return img
    }
    

提交回复
热议问题