I have regular NSImage from iPhone and the drawing get's extremely choppy during window resize (especially at small window sizes below 100px). When the window size is large there is no problem with drawing and CPU utilization is low. I have tried kCGImageSourceDecodeToSDR + or another NSImage from CGImage but the CPU utilization is extreme at small sizes.
Non-HDR images don't have problems with drawing at small sizes.
Video example: https://youtu.be/x8iAYGCyACs
import AppKit
import AVFoundation
class ImageBackgroundView: NSView {
@Invalidating(.display) var image: NSImage? = nil
override var clipsToBounds: Bool {
set { }
get { true }
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
NSColor.red.setFill()
dirtyRect.fill()
guard let image = image else { return }
// Calculate aspect-fit rect using AVFoundation
let imageSize = image.size
let targetRect = bounds
let drawRect = AVMakeRect(aspectRatio: imageSize, insideRect: targetRect)
image.draw(in: drawRect)
}
}
Copy
import Cocoa
import UniformTypeIdentifiers
class ViewController: NSViewController {
@IBOutlet weak var imageView: ImageBackgroundView!
@IBAction func buttonAction(_ sender: Any) {
let panel = NSOpenPanel()
panel.allowedContentTypes = NSImage.imageTypes.compactMap { UTType($0) }
panel.begin { response in
let nonHDROptions = [
kCGImageSourceDecodeRequest : kCGImageSourceDecodeToSDR,
kCGImageSourceDecodeRequestOptions: [kCGComputeHDRStats: false]
] as CFDictionary
guard response == .OK, let url = panel.url,
let source = CGImageSourceCreateWithURL(url as CFURL, nil),
let cgImage = CGImageSourceCreateImageAtIndex(source, 0, nonHDROptions) else { return }
self.imageView.image = NSImage(cgImage: cgImage, size: NSMakeSize(CGFloat(cgImage.width), CGFloat(cgImage.height)))
}
}
}
Time profiler with HDR NSImage:
Time profiler with NSImage + kCGImageSourceDecodeToSDR:
1
0
88