2019-04-12 00:53:03 +02:00
|
|
|
//
|
|
|
|
// RSImage-Extensions.swift
|
|
|
|
// RSCore
|
|
|
|
//
|
|
|
|
// Created by Maurice Parker on 4/11/19.
|
|
|
|
// Copyright © 2019 Ranchero Software. All rights reserved.
|
|
|
|
//
|
|
|
|
|
2020-01-17 03:09:18 +01:00
|
|
|
#if os(macOS)
|
|
|
|
import AppKit
|
|
|
|
#else
|
|
|
|
import UIKit
|
|
|
|
#endif
|
2024-03-21 04:49:15 +01:00
|
|
|
import Core
|
2019-04-12 00:53:03 +02:00
|
|
|
|
|
|
|
extension RSImage {
|
|
|
|
|
2024-03-23 19:45:16 +01: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-25 02:49:39 +01:00
|
|
|
static func scaledForIcon(_ data: Data) async -> RSImage? {
|
2024-03-23 19:45:16 +01:00
|
|
|
|
2024-03-25 02:49:39 +01:00
|
|
|
await IconScalerQueue.shared.scaledForIcon(data)
|
2019-04-12 00:53:03 +02:00
|
|
|
}
|
2019-05-15 07:44:06 +02:00
|
|
|
|
2019-11-06 01:05:57 +01:00
|
|
|
static func scaledForIcon(_ data: Data) -> RSImage? {
|
2024-03-23 19:45:16 +01:00
|
|
|
|
|
|
|
guard var cgImage = RSImage.scaleImage(data, maxPixelSize: Self.scaledMaxPixelSize) else {
|
2019-04-12 00:53:03 +02:00
|
|
|
return nil
|
|
|
|
}
|
2019-09-17 05:07:07 +02:00
|
|
|
|
2019-04-12 00:53:03 +02:00
|
|
|
#if os(iOS)
|
|
|
|
return RSImage(cgImage: cgImage)
|
|
|
|
#else
|
2019-04-13 22:05:45 +02:00
|
|
|
let size = NSSize(width: cgImage.width, height: cgImage.height)
|
2019-04-12 00:53:03 +02:00
|
|
|
return RSImage(cgImage: cgImage, size: size)
|
2019-09-17 05:07:07 +02:00
|
|
|
#endif
|
2019-06-14 22:33:13 +02:00
|
|
|
}
|
|
|
|
}
|
2020-03-20 06:22:58 +01:00
|
|
|
|
|
|
|
// MARK: - IconScalerQueue
|
|
|
|
|
2024-03-23 19:45:16 +01:00
|
|
|
private final class IconScalerQueue: @unchecked Sendable {
|
2020-03-20 06:22:58 +01: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-25 02:49:39 +01:00
|
|
|
private func scaledForIcon(_ data: Data, _ imageResultBlock: @escaping ImageResultBlock) {
|
2020-03-20 06:22:58 +01:00
|
|
|
queue.async {
|
|
|
|
let image = RSImage.scaledForIcon(data)
|
2024-03-25 02:49:39 +01:00
|
|
|
imageResultBlock(image)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func scaledForIcon(_ data: Data) async -> RSImage? {
|
|
|
|
|
|
|
|
await withCheckedContinuation { continuation in
|
|
|
|
|
|
|
|
self.scaledForIcon(data) { image in
|
|
|
|
continuation.resume(returning: image)
|
2020-03-20 06:22:58 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|