一个 Swift 5 编写的,兼容 Objective-C 的类,模仿了 macOS 颜色面板中的放大镜功能。
API 兼容 NSColorSampler (macOS 10.15 Catalina 及更高版本)
改编自 https://github.com/wentingliu/ScreenPicker,使用 Swift 5 编写,修复了错误并进行了一些小的改进。
所有功劳归于原始作者 (Wenting Liu),许可协议改编自 WTFPL
Apple 在 macOS 10.15+ 中发布了 NSColorSampler
,但对于那些仍然需要支持早期系统的用户来说,用处不大。
将 https://github.com/dagronf/DSFColorSampler
添加到您的项目中。
将 DSFColorSampler.swift
添加到您的项目中。
显示颜色放大镜,并在用户选择颜色时调用提供的完成 block。
DSFColorSampler.show { (selectedColor) in
if let selectedColor = selectedColor {
// Do something with selectedColor
}
else {
// User cancelled
}
}
[DSFColorSampler showWithLocationChange:^(NSImage* snapshot, NSColor* color) {
//
} selectionHandler:^(NSColor* color) {
//
}];
显示颜色放大镜,并为鼠标移动和选择提供回调 block。对于鼠标移动,还会提供鼠标区域的图像快照。
DSFColorSampler.show(
locationChange: { (image, currentColor) in
// Do something with the image and currentColor at the new location
},
selectionHandler: { (selectedColor) in
// Do something with selectedColor
}
)
仅限 macOS 10.15+
此库使用 sample()
方法支持 Swift 5.5 中的新 async/await 模型
Task { [weak self] in
self?.selectedColor = await DSFColorSampler.sample()
}
sample()
方法标记为 @MainActor
,因此保证在主线程上运行。
请注意,如果您使用此调用,您最好使用 macOS 10.15+ 中的 NSColorSampler 类。此功能是作为学习练习而提供的,展示了如何将基于回调的异步调用转换为基于 Task 的调用。
selectColor
函数已添加到 DSFColorSampler 中,该函数在 10.15 或更高版本上调用 NSColorSampler().show()
,并在 10.15 之前的系统上调用 DSFColorSampler().show()
。
DSFColorSampler.selectColor { (selectedColor: NSColor?) in
// Do something with selectedColor
}
[DSFColorSampler selectColorWithSelectionHandler:^(NSColor* _Nullable selectedColor) {
// Do something with
} ];
DSFColorSampler.swift
复制到您的项目中,在更早的 macOS 版本中使用此库)selectColor
静态方法,为 macOS 10.15 之前的系统提供回退功能。MIT License
Copyright (c) 2021 Darren Ford
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.