最早看到这个电子木鱼是在抖音刀叔的视频中,最近貌似在圈内火了,恰逢课上在讲多媒体编程,简单实现一个。
- SwiftUI 搭建界面与动画。
import SwiftUI
struct ContentView: View {
@State private var title = "功德值"
@State private var total = 0
@State private var once = 1
@State private var isTapped = false
var body: some View {
NavigationView {
VStack {
if isTapped {
Text("\(title) + \(once) 👍")
.font(.title3)
}
Image("muyu")
.resizable()
.scaledToFit()
.frame(width: 200)
.scaleEffect(isTapped ? 0.95 : 1.0)
.animation(.easeInOut, value: isTapped)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.black)
.navigationTitle("\(title): \(total)")
.preferredColorScheme(.dark)
.onTapGesture {
total += once
withAnimation {
isTapped.toggle()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
self.isTapped.toggle()
}
}
AudioTools.shared.playSound()
}
}
}
}
- 播放音效。
import AVFoundation
class AudioTools {
static let shared = AudioTools()
private init() {
}
func playSound() {
var soundID: SystemSoundID = 0
let soundURL = Bundle.main.url(forResource: "muyu.mp3", withExtension: nil)
if let soundURL = soundURL {
AudioServicesCreateSystemSoundID(soundURL as CFURL, &soundID)
AudioServicesPlaySystemSound(soundID)
}
}
}
- 效果。
电子木鱼效果.gif
- 代码地址。