-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathImageFileView.swift
More file actions
53 lines (44 loc) · 1.47 KB
/
ImageFileView.swift
File metadata and controls
53 lines (44 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//
// ImageFileView.swift
// CodeEdit
//
// Created by Paul Ebose on 2024/5/9.
//
import SwiftUI
/// A view for previewing an image, while respecting its dimensions.
///
/// It receives a URL to an image file and attempts to preview it.
///
/// ```swift
/// ImageFileView(imageURL)
/// ```
/// This implementation allows for proper image scaling, especially when the image dimensions are smaller than
/// the size of the image view area.
///
/// If the preview image cannot be created, it shows a *"Cannot preview image"* text.
struct ImageFileView: View {
/// URL of the image you want to preview.
private let imageURL: URL
init(_ imageURL: URL) {
self.imageURL = imageURL
}
var body: some View {
if let nsImage = NSImage(contentsOf: imageURL),
let imageReps = nsImage.representations.first {
let pixelWidth = CGFloat(imageReps.pixelsWide)
let pixelHeight = CGFloat(imageReps.pixelsHigh)
GeometryReader { proxy in
ZStack {
AnyFileView(imageURL)
.frame(
maxWidth: min(pixelWidth, proxy.size.width, nsImage.size.width),
maxHeight: min(pixelHeight, proxy.size.height, nsImage.size.height)
)
}
.frame(width: proxy.size.width, height: proxy.size.height)
}
} else {
Text("Cannot preview image")
}
}
}