Add avatar in account selector menu

This commit is contained in:
Thomas Ricouard 2023-02-09 07:36:23 +01:00
parent 8dbb57b9f6
commit abff7091cb
3 changed files with 35 additions and 6 deletions

View file

@ -1,15 +1,19 @@
import Models
import Network
import SwiftUI
import DesignSystem
@MainActor
public class AppAccountViewModel: ObservableObject {
private static var avatarsCache: [String: UIImage] = [:]
var appAccount: AppAccount
let client: Client
let isCompact: Bool
@Published var account: Account?
@Published var roundedAvatar: UIImage?
var acct: String {
if let acct = appAccount.accountName {
return acct
@ -31,8 +35,17 @@ public class AppAccountViewModel: ObservableObject {
appAccount.accountName = "\(account.acct)@\(appAccount.server)"
try appAccount.save()
}
} catch {
print(error)
}
if let account {
if let image = Self.avatarsCache[account.id] {
self.roundedAvatar = image
} else if let (data, _) = try? await URLSession.shared.data(from: account.avatar),
let image = UIImage(data: data)?.roundedImage {
self.roundedAvatar = image
Self.avatarsCache[account.id] = image
}
}
} catch { }
}
}

View file

@ -81,8 +81,8 @@ public struct AppAccountsSelectorView: View {
HapticManager.shared.fireHaptic(of: .buttonPress)
} label: {
HStack {
if viewModel.account?.id == currentAccount.account?.id {
Image(systemName: "checkmark.circle.fill")
if let image = viewModel.roundedAvatar {
Image(uiImage: image)
}
Text("\(viewModel.account?.displayName ?? "")")
}

View file

@ -0,0 +1,16 @@
import UIKit
extension UIImage{
public var roundedImage: UIImage? {
let rect = CGRect(origin:CGPoint(x: 0, y: 0), size: self.size)
UIGraphicsBeginImageContextWithOptions(self.size, false, 1)
defer { UIGraphicsEndImageContext() }
UIBezierPath(
roundedRect: rect,
cornerRadius: self.size.height
).addClip()
self.draw(in: rect)
return UIGraphicsGetImageFromCurrentImageContext()
}
}