SwiftUI短短幾行代碼可以實(shí)現(xiàn)復(fù)雜的布局,還可以做出比較炫的效果。先看一下用戶頭像發(fā)光的效果吧!
用戶頭像發(fā)光效果.png
用戶頭像的發(fā)光是給用戶頭像分層加陰影,讓陰影看起來比周圍亮,看起來就是發(fā)光效果。
ZStack(alignment:.center) {
Circle()
.fill(Color.white)
.frame(width: 60, height: 60 ,alignment: .center)
.glow()
Image("user_img")
.resizable()
.frame(width: 60, height: 60, alignment: Alignment.center)
.cornerRadius(30)
}.frame(width: 72, height: 72, alignment: .leading)
.padding(EdgeInsets(top: 12, leading: 30, bottom: 12, trailing: 12))
上面代碼的glow是View的拓展,主要通過三層陰影實(shí)現(xiàn)的發(fā)光效果。另外添加了一層模糊效果,讓發(fā)光看起來更加真實(shí)。
extension View {
func glow(radius: CGFloat = 20) -> some View {
return self
.overlay(self.blur(radius: radius / 6))
.shadow(color: .shadowColor, radius: radius / 3)
.shadow(color: .shadowColor, radius: radius / 3)
.shadow(color: .shadowColor, radius: radius / 3)
}
}
用戶昵稱的彩虹字體是背景漸變、一些模糊和一些遮罩來創(chuàng)建彩虹輝光。使用ForEach創(chuàng)建兩個(gè)矩形,每個(gè)矩形都以精確的大小填充彩虹梯度。然后使用調(diào)用此方法的任何視圖遮蓋漸變時(shí),然后用5點(diǎn)模糊或無模糊覆蓋原始視圖。
extension View {
func multicolorGlow() -> some View {
ZStack {
ForEach(0..<2) { i in
Rectangle()
.fill(AngularGradient(gradient: Gradient(colors: [.red, .yellow, .green, .blue, .purple, .red]), center: .center))
.frame(width: 100, height: 60)
.mask(self.blur(radius: 10))
.overlay(self.blur(radius: 5 - CGFloat(i * 5)))
}
}
}
}