~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/old-fella

Old people's social media app

0
1
main
158 lines · 6.3 KB Raw History
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)
        }
    }
}