Files
Pulse/Sources/PulseUI/Views/ImageViewer.swift
2024-08-04 11:07:42 -04:00

73 lines
2.4 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// The MIT License (MIT)
//
// Copyright (c) 2020-2024 Alexander Grebenyuk (github.com/kean).
import SwiftUI
import Pulse
struct ImageViewer: View {
let viewModel: ImagePreviewViewModel
var body: some View {
VStack(spacing: 16) {
Image(uxImage: viewModel.image)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(maxWidth: viewModel.image.size.width, maxHeight: viewModel.image.size.height)
.border(Color.separator, width: 0.5)
HStack {
TextView(string: viewModel.info)
Spacer()
}
Spacer()
}.padding()
}
}
struct ImagePreviewViewModel {
let image: UXImage
let info: NSAttributedString
init(image: UXImage, data: Data, context: FileViewerViewModelContext) {
func intValue(for key: String) -> Int? {
context.metadata?[key].flatMap { Int($0) }
}
let isShowingOriginal = Int64(data.count) == context.originalSize
let originalImageSize: CGSize?
if isShowingOriginal {
originalImageSize = image.size
} else if context.isResponse {
if let width = intValue(for: "ResponsePixelWidth"),
let height = intValue(for: "ResponsePixelHeight") {
originalImageSize = CGSize(width: width, height: height)
} else {
originalImageSize = nil
}
} else {
if let width = intValue(for: "RequestPixelWidth"),
let height = intValue(for: "RequestPixelHeight") {
originalImageSize = CGSize(width: width, height: height)
} else {
originalImageSize = nil
}
}
var info: [(String, String?)] = [
("Resolution", originalImageSize.map { "\(Int($0.width)) × \(Int($0.height)) px" }),
("Size", ByteCountFormatter.string(fromByteCount: context.originalSize)),
("Type", context.contentType?.rawValue),
("Displayed", isShowingOriginal ? "original image" : "preview (original not saved)")
]
if !isShowingOriginal {
info.append(("Preview Size (Decompressed)", ByteCountFormatter.string(fromByteCount: Int64(data.count))))
}
self.image = image
let section = KeyValueSectionViewModel(title: "Image", color: .pink, items: info)
self.info = TextRenderer().render(section)
}
}