forked from shadowfacts/Tusker
65 lines
1.7 KiB
Swift
65 lines
1.7 KiB
Swift
//
|
|
// ComposeAvatarImageView.swift
|
|
// Tusker
|
|
//
|
|
// Created by Shadowfacts on 8/18/20.
|
|
// Copyright © 2020 Shadowfacts. All rights reserved.
|
|
//
|
|
|
|
import SwiftUI
|
|
|
|
struct ComposeAvatarImageView: View {
|
|
let url: URL?
|
|
@State var request: ImageCache.Request? = nil
|
|
@State var avatarImage: UIImage? = nil
|
|
@ObservedObject var preferences = Preferences.shared
|
|
|
|
var body: some View {
|
|
image
|
|
.resizable()
|
|
.conditionally(url != nil) {
|
|
$0.onAppear(perform: self.loadImage)
|
|
}
|
|
.onDisappear(perform: self.cancelRequest)
|
|
}
|
|
|
|
private var image: Image {
|
|
if let avatarImage = avatarImage {
|
|
return Image(uiImage: avatarImage).renderingMode(.original)
|
|
} else {
|
|
return placeholderImage
|
|
}
|
|
}
|
|
|
|
private var placeholderImage: Image {
|
|
let imageName: String
|
|
switch preferences.avatarStyle {
|
|
case .circle:
|
|
imageName = "person.crop.circle"
|
|
case .roundRect:
|
|
imageName = "person.crop.square"
|
|
}
|
|
return Image(systemName: imageName)
|
|
}
|
|
|
|
private func loadImage() {
|
|
guard let url = url else { return }
|
|
request = ImageCache.avatars.get(url) { (_, image) in
|
|
DispatchQueue.main.async {
|
|
self.request = nil
|
|
self.avatarImage = image
|
|
}
|
|
}
|
|
}
|
|
|
|
private func cancelRequest() {
|
|
request?.cancel()
|
|
}
|
|
}
|
|
|
|
struct ComposeAvatarImageView_Previews: PreviewProvider {
|
|
static var previews: some View {
|
|
ComposeAvatarImageView(url: URL(string: "https://social.shadowfacts.net/media/4b481afc591a8f3d11d0f5732e5cb320422dec72d7f223ebb5f35d5d0e821a9c.png")!)
|
|
}
|
|
}
|