如何获取文件的com.apple.icns数据用于填充粘贴板?
生成com.apple.icns类型粘贴板数据的解决方案
直接读取现成的.icns文件
要是你处理的是应用程序(.app包)这类本身带.icns文件的资源,直接去包的Contents/Resources目录里读取对应的.icns文件数据就行:if let appURL = Bundle.main.url(forResource: "AppIcon", withExtension: "icns") { do { let icnsData = try Data(contentsOf: appURL) // 写入粘贴板 let pasteboard = NSPasteboard.general pasteboard.clearContents() pasteboard.setData(icnsData, forType: NSPasteboard.PasteboardType(rawValue: "com.apple.icns")) } catch { print("读取icns文件失败: \(error)") } }从NSImage转成.icns格式
普通文件的图标可以通过NSWorkspace拿到NSImage,再把它转成完整的.icns数据——NSImage本身包含多分辨率图,转成.icns后会保留这些信息:func icnsData(from image: NSImage) -> Data? { guard !image.representations.isEmpty else { return nil } let bitmapRep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(image.size.width), pixelsHigh: Int(image.size.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .calibratedRGB, bytesPerRow: 0, bitsPerPixel: 0) bitmapRep?.size = image.size let context = NSGraphicsContext(bitmapImageRep: bitmapRep!) NSGraphicsContext.saveGraphicsState() NSGraphicsContext.current = context image.draw(at: .zero, from: .zero, operation: .copy, fraction: 1.0) NSGraphicsContext.restoreGraphicsState() return bitmapRep?.representation(using: .icns, properties: [:]) } // 使用示例:拿文件图标转成icns再写入粘贴板 let fileURL = URL(fileURLWithPath: "/path/to/your/file") if let icon = NSWorkspace.shared.icon(forFile: fileURL.path) { if let icnsData = icnsData(from: icon) { let pasteboard = NSPasteboard.general pasteboard.clearContents() pasteboard.setData(icnsData, forType: NSPasteboard.PasteboardType(rawValue: "com.apple.icns")) } }用LaunchServices拿原生icns数据
系统文件或已注册类型的文件,用LaunchServices的接口能拿到更原生的.icns数据,比NSImage转的更贴近Finder复制的效果:import CoreServices func icnsDataForFile(at url: URL) -> Data? { var iconRef: IconRef? let status = LSCopyIconRefForURL(url as CFURL, kLSIconSizeNormal, &iconRef) guard status == noErr, let icon = iconRef else { return nil } var data: CFData? if IconRefCopyData(icon, kIconServicesFormatICNS, &data) == noErr { return data as Data? } return nil } // 使用示例 let fileURL = URL(fileURLWithPath: "/path/to/your/file") if let icnsData = icnsDataForFile(at: fileURL) { let pasteboard = NSPasteboard.general pasteboard.clearContents() pasteboard.setData(icnsData, forType: NSPasteboard.PasteboardType(rawValue: "com.apple.icns")) }
内容的提问来源于stack exchange,提问作者Thomas Tempelmann
相关产品推荐
相关产品推荐

