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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
import SwiftUI
struct AvatarCropView: View {
@Environment(\.dismiss) private var dismiss
@GestureState private var adjustment = CropGestureAdjustment()
@State private var crop = AvatarCrop()
@State private var isRendering = false
@State private var showsError = false
let image: UIImage
let onUse: (Data) -> Void
var body: some View {
VStack(spacing: 16) {
GeometryReader { geometry in
let side = min(geometry.size.width, geometry.size.height, 480)
cropArea(side: side)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
Text("Drag or pinch to crop.")
.appFont(.footnote)
.foregroundStyle(.secondary)
HStack(spacing: 12) {
Button("Rotate", systemImage: "rotate.right") { crop.rotateClockwise() }
Button("Flip", systemImage: "arrow.left.and.right") { crop.flipHorizontally() }
.accessibilityAddTraits(crop.isFlipped ? .isSelected : [])
}
.controlSize(.large)
.buttonStyle(.bordered)
.padding(.bottom, 8)
}
.padding(16)
.disabled(isRendering)
.appNavigationTitle("Crop Avatar")
.navigationBarBackButtonHidden(true)
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Cancel", role: .cancel) { dismiss() }
.disabled(isRendering)
}
ToolbarItem(placement: .confirmationAction) {
if isRendering {
ProgressView().accessibilityLabel("Cropping photo")
} else {
Button("Use Photo") { usePhoto() }
}
}
}
.alert("Could Not Crop Photo", isPresented: $showsError) {
Button("OK", role: .cancel) {}
} message: {
Text("Try again or choose another photo.")
}
}
private func cropArea(side: CGFloat) -> some View {
let preview = adjustedCrop(adjustment)
let imageSize = preview.scaledImageSize(for: image.size)
return Rectangle()
.fill(.black)
.frame(width: side, height: side)
.overlay {
Image(uiImage: image)
.resizable()
.frame(width: imageSize.width * side, height: imageSize.height * side)
.rotationEffect(.degrees(Double(preview.quarterTurns) * 90))
.scaleEffect(x: preview.isFlipped ? -1 : 1, y: 1)
.offset(x: preview.offset.width * side, y: preview.offset.height * side)
}
.clipped()
.overlay { cropGrid.allowsHitTesting(false) }
.contentShape(Rectangle())
.gesture(cropGesture(side: side))
.accessibilityElement(children: .ignore)
.accessibilityLabel("Crop area")
.accessibilityValue("\(Int((preview.zoom * 100).rounded())) percent")
.accessibilityIdentifier("avatarCropArea")
.accessibilityAdjustableAction { direction in
switch direction {
case .increment: crop.magnify(by: 1.25, anchor: .zero, imageSize: image.size)
case .decrement: crop.magnify(by: 0.8, anchor: .zero, imageSize: image.size)
@unknown default: break
}
}
.accessibilityAction(named: "Move Up") { movePhoto(width: 0, height: -0.1) }
.accessibilityAction(named: "Move Down") { movePhoto(width: 0, height: 0.1) }
.accessibilityAction(named: "Move Left") { movePhoto(width: -0.1, height: 0) }
.accessibilityAction(named: "Move Right") { movePhoto(width: 0.1, height: 0) }
}
private var cropGrid: some View {
Canvas { context, size in
var lines = Path()
for fraction in [CGFloat(1) / 3, CGFloat(2) / 3] {
let guide = size.width * fraction
lines.move(to: CGPoint(x: guide, y: 0))
lines.addLine(to: CGPoint(x: guide, y: size.height))
lines.move(to: CGPoint(x: 0, y: guide))
lines.addLine(to: CGPoint(x: size.width, y: guide))
}
context.stroke(lines, with: .color(.white.opacity(0.45)), lineWidth: 1)
}
.border(.white.opacity(0.7))
}
private func cropGesture(side: CGFloat) -> some Gesture {
MagnifyGesture().simultaneously(with: DragGesture(minimumDistance: 3))
.updating($adjustment) { value, adjustment, _ in
adjustment = CropGestureAdjustment(pinch: value.first, drag: value.second, side: side)
}
.onEnded { value in
crop = adjustedCrop(CropGestureAdjustment(pinch: value.first, drag: value.second, side: side))
}
}
private func adjustedCrop(_ adjustment: CropGestureAdjustment) -> AvatarCrop {
var adjusted = crop
adjusted.magnify(by: adjustment.magnification, anchor: adjustment.anchor, imageSize: image.size)
adjusted.pan(by: adjustment.translation, imageSize: image.size)
return adjusted
}
private func movePhoto(width: CGFloat, height: CGFloat) {
crop.pan(by: CGSize(width: width, height: height), imageSize: image.size)
}
private func usePhoto() {
let selection = crop
isRendering = true
Task {
defer { isRendering = false }
do {
let data = try await Task.detached(priority: .userInitiated) {
try selection.jpegData(from: image)
}.value
onUse(data)
dismiss()
} catch {
showsError = true
}
}
}
}
private struct CropGestureAdjustment {
var magnification: CGFloat = 1
var anchor = CGPoint.zero
var translation = CGSize.zero
init(pinch: MagnifyGesture.Value? = nil, drag: DragGesture.Value? = nil, side: CGFloat = 1) {
if let pinch {
magnification = pinch.magnification
anchor = CGPoint(x: pinch.startAnchor.x - 0.5, y: pinch.startAnchor.y - 0.5)
}
if let drag, side > 0 {
translation = CGSize(width: drag.translation.width / side, height: drag.translation.height / side)
}
}
}