Im trying create magnify view but have some problems that can't understand.
I have NSWindow
that contains NSImageView
. When I set static origin point position to window, and moving only cursor (mouse), all captured fine. But when I set origin point to window from mouse location, image is huge blurred.
In image.addRepresentation(bitmap) I receiving normal image as I expected (that's was checked on debugger). Also in debug mode I saw that captured image fast zoomed from normal to huge when mouse moving.
Any suggestions?
NSWindow:
class ColorPickerWindow: NSWindow {
private let colorPickerMagnifier: ColorPickerMagnifier!
override init(contentRect: NSRect, styleMask style: NSWindow.StyleMask, backing backingStoreType: NSWindow.BackingStoreType, defer flag: Bool) {
self.colorPickerMagnifier = ColorPickerMagnifier()
let location = NSEvent.mouseLocation
super.init(contentRect: NSRect(x: 0, y: 0, width: 120, height: 120),
styleMask: [],
backing: .buffered,
defer: true)
self.backgroundColor = .clear
self.level = .floating + 1000
self.makeKeyAndOrderFront(self)
self.isMovableByWindowBackground = false
self.isOpaque = false
self.hasShadow = false
NSEvent.addLocalMonitorForEvents(matching: .mouseMoved) { (event) -> NSEvent in
let location = NSEvent.mouseLocation
self.updatePickerLocation(location: location)
print(location)
return event
}
self.colorPickerMagnifier.frame = self.contentView!.bounds
self.contentView?.addSubview(self.colorPickerMagnifier)
self.updatePickerLocation(location: location)
}
// MARK: - Private
private func updatePickerLocation(location: CGPoint) {
self.updatePickerImage(from: location)
self.setFrameOrigin(NSPoint(x: location.x - self.contentView!.frame.width / 2, y: location.y - self.contentView!.frame.height / 2))
}
private func updatePickerImage(from location: CGPoint) {
let magnifySize = CGFloat(8)
let x = floor(location.x) - floor(magnifySize / 2)
let y = (NSScreen.main?.frame)!.size.height - floor(location.y) - floor(magnifySize / 2)
let captureRect = CGRect(x: x, y: y, width: magnifySize, height: magnifySize)
guard let cgImageFromScreen = CGWindowListCreateImage(captureRect, .optionOnScreenAboveWindow, .zero, .bestResolution) else {
return
}
let bitmap = NSBitmapImageRep(cgImage: cgImageFromScreen)
let image = NSImage()
image.addRepresentation(bitmap)
self.colorPickerMagnifier.image = image
}
}
NSImageView:
class ColorPickerMagnifier: ImageViewDeInterpolated {
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.imageScaling = .scaleProportionallyUpOrDown
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
}
}