Canvatorium Visio Lab 5043
SwiftUI Custom Hover Effect
Learning how to use Custom Hover Effects in SwiftUI. Stacking multiple effects to adjust opacity while changing scale with an anchor.
struct Lab5043: View {
let count: Int = 12
let radius: CGFloat = 160
var body: some View {
ZStack {
Lab5043Eyes()
.font(.extraLargeTitle2)
ForEach(0..<count, id: \.self) { index in
Lab5043Eyes()
.offset(x: circularXPosition(index: index), y: circularYPosition(index: index))
}
}
.frame(width: 500, height: 500)
}
func circularXPosition(index: Int) -> CGFloat {
let angle = Double(index) / Double(count) * 2 * .pi
return radius * cos(angle)
}
func circularYPosition(index: Int) -> CGFloat {
let angle = Double(index) / Double(count) * 2 * .pi
return radius * sin(angle)
}
}
struct Lab5043Eyes: View {
var body: some View {
Text("🐸")
.font(.system(size: 72))
.hoverEffect(FadeHoverEffect())
.hoverEffect(ScaleHoverEffect())
}
}
struct FadeHoverEffect: CustomHoverEffect {
func body(content: Content) -> some CustomHoverEffect {
content.hoverEffect { effect, isActive, proxy in
effect.animation(.easeOut) {
$0.opacity(isActive ? 0.4 : 0.9)
}
}
}
}
struct ScaleHoverEffect: CustomHoverEffect {
func body(content: Content) -> some CustomHoverEffect {
content.hoverEffect { effect, isActive, proxy in
effect.animation(.easeOut) {
$0.scaleEffect(isActive ? CGSize(width: 0.4, height: 0.4) : CGSize(width: 1, height: 1), anchor: .bottom)
}
}
}
}