在 Swift 中使用 Cocoa 捕获屏幕并缩放图像,可以按以下步骤实现:
AppKit
框架,因为在 macOS 应用开发中,AppKit
提供了与用户界面和系统交互的功能。
import AppKit
CGWindowListCreateImage
函数来获取屏幕截图。这个函数需要指定要捕获的窗口列表选项和一个矩形区域来定义捕获范围。如果要捕获整个屏幕,可以使用CGDisplayBounds
函数获取屏幕的边界。
func captureScreen() -> NSImage? { let screenRect = NSScreen.main?.frame?? NSRect.zero guard let image = CGWindowListCreateImage( screenRect, .optionOnScreenOnly, CGWindowID(kCGNullWindowID), [.nominalResolution] ) else { return nil } return NSImage(cgImage: image, size: NSSize(width: image.width, height: image.height)) }NSImage
进行缩放。
func scaleImage(image: NSImage, scaleFactor: CGFloat) -> NSImage? { let newWidth = image.size.width * scaleFactor let newHeight = image.size.height * scaleFactor let newSize = NSSize(width: newWidth, height: newHeight) let scaledImage = NSImage(size: newSize) scaledImage.lockFocus() image.draw(in: NSRect(origin:.zero, size: newSize), from:.zero, operation:.copy, fraction: 1.0) scaledImage.unlockFocus() return scaledImage }NSBitmapImageRep
将NSImage
转换为指定格式(如 PNG)的数据,并保存到文件。
func saveImage(image: NSImage, to url: URL) -> Bool { guard let rep = image.representations.first as? NSBitmapImageRep else { return false } let data = rep.representation(using:.png, properties: [:]) do { try data?.write(to: url) return true } catch { print("Error saving image: \(error)") return false } }
以上代码展示了如何在 Swift 中使用 Cocoa 捕获屏幕、缩放图像并保存为文件。确保在实际应用中处理好错误情况,并根据需求调整代码。例如,你可能需要处理不同的图像格式、更好的文件路径管理等。
领取专属 10元无门槛券
手把手带您无忧上云