Last active
January 18, 2021 22:47
-
-
Save davidseek/d5eb6036dd7be5b565694a674b5e3908 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import SwiftUI | |
struct Canvas { | |
// The image for SwiftUI View | |
let image: Image | |
// The CGImage for further processing | |
let screenshot: CGImage | |
// Failable initializer | |
init?() { | |
// Reference for the number of displays we have | |
var displayCount: UInt32 = 0; | |
// Updating displayCount as inout variable | |
var result = CGGetActiveDisplayList(0, nil, &displayCount) | |
// If we encounter issues here, we want to fail | |
guard result == CGError.success else { | |
// MARK: - TODO, Handle appropriatly | |
return nil | |
} | |
// Get references to out active displays | |
let activeDisplays = UnsafeMutablePointer<CGDirectDisplayID> | |
.allocate(capacity: Int(displayCount)) | |
// Update our Core Graphics result object | |
result = CGGetActiveDisplayList(displayCount, activeDisplays, &displayCount) | |
// If we encounter issues here, we want to fail | |
guard result == CGError.success else { | |
// MARK: - TODO, Handle appropriatly | |
return nil | |
} | |
// I only care for the my iMac's display, so I hard-code it | |
let desktop: CGImage = CGDisplayCreateImage(activeDisplays[Int(0)])! | |
// Now I'm getting the hard-coded area my desktop is in | |
// This takes some trial and error | |
let area = Rect.getTable(in: desktop) | |
// Crop the desktop to remain with the Poker table | |
self.screenshot = desktop.cropping(to: area)! | |
// Lastly turn the image into an image we can display in SwiftUI | |
// The idea here is to get a visual representation. | |
// So we can check if `desktop` and `area` are proper values | |
self.image = Image(nsImage: self.screenshot.asNSImage()!) | |
} | |
} | |
// Rect is simply a lightweight type used to keep the code clean | |
enum Rect { | |
// This is our hard-coded location of the poker table on my desktop. | |
static func getTable(in screenshot: CGImage) -> CGRect {...} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment