2019-04-11 17:53:03 -05:00
|
|
|
//
|
|
|
|
// RSImage-Extensions.swift
|
|
|
|
// RSCore
|
|
|
|
//
|
|
|
|
// Created by Maurice Parker on 4/11/19.
|
|
|
|
// Copyright © 2019 Ranchero Software. All rights reserved.
|
|
|
|
//
|
|
|
|
|
2020-01-16 20:09:18 -06:00
|
|
|
#if os(macOS)
|
|
|
|
import AppKit
|
|
|
|
#else
|
|
|
|
import UIKit
|
|
|
|
#endif
|
2024-03-20 20:49:15 -07:00
|
|
|
import Core
|
2019-04-11 17:53:03 -05:00
|
|
|
|
|
|
|
extension RSImage {
|
|
|
|
|
2024-03-23 11:45:16 -07:00
|
|
|
private static let scaledMaxPixelSize: Int = {
|
|
|
|
|
|
|
|
let maxIconSize = 48
|
|
|
|
#if os(iOS)
|
|
|
|
let maxScreenScale = 3
|
|
|
|
#elseif os(macOS)
|
|
|
|
let maxScreenScale = 2
|
|
|
|
#endif
|
|
|
|
|
|
|
|
return maxIconSize * maxScreenScale
|
|
|
|
}()
|
|
|
|
|
2024-03-24 18:49:39 -07:00
|
|
|
static func scaledForIcon(_ data: Data) async -> RSImage? {
|
2024-03-23 11:45:16 -07:00
|
|
|
|
2024-03-24 18:49:39 -07:00
|
|
|
await IconScalerQueue.shared.scaledForIcon(data)
|
2019-04-11 17:53:03 -05:00
|
|
|
}
|
2019-05-14 22:44:06 -07:00
|
|
|
|
2019-11-05 18:05:57 -06:00
|
|
|
static func scaledForIcon(_ data: Data) -> RSImage? {
|
2024-03-23 11:45:16 -07:00
|
|
|
|
|
|
|
guard var cgImage = RSImage.scaleImage(data, maxPixelSize: Self.scaledMaxPixelSize) else {
|
2019-04-11 17:53:03 -05:00
|
|
|
return nil
|
|
|
|
}
|
2019-09-16 20:07:07 -07:00
|
|
|
|
2019-04-11 17:53:03 -05:00
|
|
|
#if os(iOS)
|
|
|
|
return RSImage(cgImage: cgImage)
|
|
|
|
#else
|
2019-04-13 15:05:45 -05:00
|
|
|
let size = NSSize(width: cgImage.width, height: cgImage.height)
|
2019-04-11 17:53:03 -05:00
|
|
|
return RSImage(cgImage: cgImage, size: size)
|
2019-09-16 20:07:07 -07:00
|
|
|
#endif
|
2019-06-14 15:33:13 -05:00
|
|
|
}
|
|
|
|
}
|
2020-03-19 22:22:58 -07:00
|
|
|
|
|
|
|
// MARK: - IconScalerQueue
|
|
|
|
|
2024-03-23 11:45:16 -07:00
|
|
|
private final class IconScalerQueue: @unchecked Sendable {
|
2020-03-19 22:22:58 -07:00
|
|
|
|
|
|
|
static let shared = IconScalerQueue()
|
|
|
|
|
|
|
|
private let queue: DispatchQueue = {
|
|
|
|
let q = DispatchQueue(label: "IconScaler", attributes: .initiallyInactive)
|
|
|
|
q.setTarget(queue: DispatchQueue.global(qos: .default))
|
|
|
|
q.activate()
|
|
|
|
return q
|
|
|
|
}()
|
|
|
|
|
2024-03-24 18:49:39 -07:00
|
|
|
private func scaledForIcon(_ data: Data, _ imageResultBlock: @escaping ImageResultBlock) {
|
2020-03-19 22:22:58 -07:00
|
|
|
queue.async {
|
|
|
|
let image = RSImage.scaledForIcon(data)
|
2024-03-24 18:49:39 -07:00
|
|
|
imageResultBlock(image)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func scaledForIcon(_ data: Data) async -> RSImage? {
|
|
|
|
|
|
|
|
await withCheckedContinuation { continuation in
|
|
|
|
|
|
|
|
self.scaledForIcon(data) { image in
|
|
|
|
continuation.resume(returning: image)
|
2020-03-19 22:22:58 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|