Compare commits

...

2 Commits

Author SHA1 Message Date
0cde8d0c32 refactor: 盲盒流程重构 2025-09-06 14:01:05 +08:00
b851e32eda refactor: 将盲盒View拆出来 2025-09-06 13:12:35 +08:00
11 changed files with 797 additions and 2044 deletions

View File

@ -1,558 +1,21 @@
import SwiftUI import SwiftUI
import SwiftData
import AVKit
// MARK: - Notification Names /// App entry content. Keeps only routing/navigation and delegates feature UIs to their own files.
extension Notification.Name { struct ContentView: View {
static let blindBoxStatusChanged = Notification.Name("blindBoxStatusChanged") @StateObject private var router = Router.shared
}
struct BlindBoxView: View {
let mediaType: BlindBoxMediaType
@State private var showModal = false //
@State private var showSettings = false //
@State private var isMember = false //
@State private var memberDate = "" //
@State private var showLogin = false
@State private var memberProfile: MemberProfile? = nil
@State private var blindCount: BlindCount? = nil
@State private var blindList: [BlindList] = [] // Changed to array
//
@State private var blindGenerate : BlindBoxData?
@State private var showLottieAnimation = true
//
@State private var isPolling = false
@State private var pollingTimer: Timer?
@State private var currentBoxType: String = ""
//
@State private var videoURL: String = ""
@State private var imageURL: String = ""
//
@State private var countdown: (minutes: Int, seconds: Int, milliseconds: Int) = (36, 50, 20)
@State private var countdownTimer: Timer?
//
@State private var displayData: BlindBoxData? = nil
@State private var showScalingOverlay = false
@State private var animationPhase: BlindBoxAnimationPhase = .loading
@State private var scale: CGFloat = 0.1
@State private var videoPlayer: AVPlayer?
@State private var showControls = false
@State private var isAnimating = true
@State private var aspectRatio: CGFloat = 1.0
@State private var isPortrait: Bool = false
@State private var displayImage: UIImage?
@State private var showMedia = false
// -
@Query private var login: [Login]
init(mediaType: BlindBoxMediaType) {
self.mediaType = mediaType
}
//
private func startCountdown() {
// 36:50:20
countdown = (36, 50, 20)
countdownTimer?.invalidate()
countdownTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { _ in
var (minutes, seconds, milliseconds) = countdown
//
milliseconds -= 10
if milliseconds < 0 {
milliseconds = 90
seconds -= 1
}
//
if seconds < 0 {
seconds = 59
minutes -= 1
}
//
if minutes <= 0 && seconds <= 0 && milliseconds <= 0 {
countdownTimer?.invalidate()
countdownTimer = nil
return
}
countdown = (minutes, seconds, milliseconds)
}
}
private func loadMedia() {
print("loadMedia called with mediaType: \(mediaType)")
switch mediaType {
case .video:
loadVideo()
currentBoxType = "Video"
startPolling()
case .image:
loadImage()
currentBoxType = "Image"
startPolling()
case .all:
print("Loading all content...")
//
NetworkService.shared.get(
path: "/membership/personal-center-info",
parameters: nil
) { (result: Result<MemberProfileResponse, NetworkError>) in
DispatchQueue.main.async {
switch result {
case .success(let response):
self.memberProfile = response.data
self.isMember = response.data.membershipLevel == "Pioneer"
self.memberDate = response.data.membershipEndAt ?? ""
print("✅ 成功获取会员信息:", response.data)
print("✅ 用户ID:", response.data.userInfo.userId)
case .failure(let error):
print("❌ 获取会员信息失败:", error)
}
}
}
//
NetworkService.shared.get(
path: "/blind_box/available/quantity",
parameters: nil
) { (result: Result<APIResponse<BlindCount>, NetworkError>) in
DispatchQueue.main.async {
switch result {
case .success(let response):
self.blindCount = response.data
print("✅ 成功获取盲盒数量:", response.data)
case .failure(let error):
print("❌ 获取数量失败:", error)
}
}
}
//
NetworkService.shared.get(
path: "/blind_boxs/query",
parameters: nil
) { (result: Result<APIResponse<[BlindList]>, NetworkError>) in
DispatchQueue.main.async {
switch result {
case .success(let response):
self.blindList = response.data ?? []
// none
if self.blindList.isEmpty {
self.animationPhase = .none
}
print("✅ 成功获取 \(self.blindList.count) 个盲盒")
case .failure(let error):
self.blindList = []
self.animationPhase = .none
print("❌ 获取盲盒列表失败:", error.localizedDescription)
}
}
}
}
}
//
private func startPolling() {
stopPolling()
isPolling = true
checkBlindBoxStatus()
}
private func stopPolling() {
pollingTimer?.invalidate()
pollingTimer = nil
isPolling = false
}
private func checkBlindBoxStatus() {
guard !currentBoxType.isEmpty else {
stopPolling()
return
}
NetworkService.shared.postWithToken(
path: "/blind_box/generate/mock",
parameters: ["box_type": currentBoxType]
) { (result: Result<APIResponse<BlindBoxData>, NetworkError>) in
DispatchQueue.main.async {
switch result {
case .success(let response):
let data = response.data
self.blindGenerate = data
print("当前盲盒状态: \(data.status)")
//
if self.mediaType == .all, let firstItem = self.blindList.first {
self.displayData = BlindBoxData(from: firstItem)
} else {
self.displayData = data
}
//
NotificationCenter.default.post(
name: .blindBoxStatusChanged,
object: nil,
userInfo: ["status": data.status]
)
if data.status != "Preparing" {
self.stopPolling()
print("✅ 盲盒准备就绪,状态: \(data.status)")
if self.mediaType == .video {
self.videoURL = data.url ?? ""
} else if self.mediaType == .image {
self.imageURL = data.url ?? ""
}
} else {
self.pollingTimer = Timer.scheduledTimer(
withTimeInterval: 2.0,
repeats: false
) { _ in
self.checkBlindBoxStatus()
}
}
case .failure(let error):
print("❌ 获取盲盒状态失败: \(error.localizedDescription)")
self.stopPolling()
}
}
}
}
private func loadImage() {
guard !imageURL.isEmpty, let url = URL(string: imageURL) else {
print("⚠️ 图片URL无效或为空")
return
}
URLSession.shared.dataTask(with: url) { data, _, _ in
if let data = data, let image = UIImage(data: data) {
DispatchQueue.main.async {
self.displayImage = image
self.aspectRatio = image.size.width / image.size.height
self.isPortrait = image.size.height > image.size.width
self.showScalingOverlay = true //
}
}
}.resume()
}
private func loadVideo() {
guard !videoURL.isEmpty, let url = URL(string: videoURL) else {
print("⚠️ 视频URL无效或为空")
return
}
let asset = AVAsset(url: url)
let playerItem = AVPlayerItem(asset: asset)
let player = AVPlayer(playerItem: playerItem)
let videoTracks = asset.tracks(withMediaType: .video)
if let videoTrack = videoTracks.first {
let size = videoTrack.naturalSize.applying(videoTrack.preferredTransform)
let width = abs(size.width)
let height = abs(size.height)
aspectRatio = width / height
isPortrait = height > width
}
//
videoPlayer = player
videoPlayer?.play()
showScalingOverlay = true //
}
private func prepareVideo() {
guard !videoURL.isEmpty, let url = URL(string: videoURL) else {
print("⚠️ 视频URL无效或为空")
return
}
let asset = AVAsset(url: url)
let playerItem = AVPlayerItem(asset: asset)
let player = AVPlayer(playerItem: playerItem)
let videoTracks = asset.tracks(withMediaType: .video)
if let videoTrack = videoTracks.first {
let size = videoTrack.naturalSize.applying(videoTrack.preferredTransform)
let width = abs(size.width)
let height = abs(size.height)
aspectRatio = width / height
isPortrait = height > width
}
//
videoPlayer = player
}
private func prepareImage() {
guard !imageURL.isEmpty, let url = URL(string: imageURL) else {
print("⚠️ 图片URL无效或为空")
return
}
URLSession.shared.dataTask(with: url) { data, _, _ in
if let data = data, let image = UIImage(data: data) {
DispatchQueue.main.async {
self.displayImage = image
self.aspectRatio = image.size.width / image.size.height
self.isPortrait = image.size.height > image.size.width
}
}
}.resume()
}
private func startScalingAnimation() {
self.scale = 0.1
self.showScalingOverlay = true
withAnimation(.spring(response: 2.0, dampingFraction: 0.5, blendDuration: 0.8)) {
self.scale = 1.0
}
}
// MARK: - Computed Properties
private var scaledWidth: CGFloat {
if isPortrait {
return UIScreen.main.bounds.height * scale * 1/aspectRatio
} else {
return UIScreen.main.bounds.width * scale
}
}
private var scaledHeight: CGFloat {
if isPortrait {
return UIScreen.main.bounds.height * scale
} else {
return UIScreen.main.bounds.width * scale * 1/aspectRatio
}
}
var body: some View { var body: some View {
ZStack { NavigationStack(path: $router.path) {
Color.themeTextWhiteSecondary.ignoresSafeArea() // Home entry: show the BlindBox home (all)
.onAppear { BlindBoxView(mediaType: .all)
print("🎯 BlindBoxView appeared with mediaType: \(mediaType)") .navigationDestination(for: AppRoute.self) { route in
print("🎯 Current thread: \(Thread.current)") route.view
//
if mediaType == .all, let firstItem = blindList.first {
displayData = BlindBoxData(from: firstItem)
} else {
displayData = blindGenerate
}
//
NotificationCenter.default.addObserver(
forName: .blindBoxStatusChanged,
object: nil,
queue: .main
) { notification in
if let status = notification.userInfo?["status"] as? String {
switch status {
case "Preparing":
withAnimation {
self.animationPhase = .loading
}
case "Unopened":
withAnimation {
self.animationPhase = .ready
}
default:
//
withAnimation {
self.animationPhase = .ready
}
break
}
}
}
//
loadMedia()
} }
.onDisappear {
stopPolling()
countdownTimer?.invalidate()
countdownTimer = nil
// Clean up video player
videoPlayer?.pause()
videoPlayer?.replaceCurrentItem(with: nil)
videoPlayer = nil
NotificationCenter.default.removeObserver(
self,
name: .blindBoxStatusChanged,
object: nil
)
}
if showScalingOverlay {
MediaOverlayView(
videoPlayer: $videoPlayer,
showControls: $showControls,
mediaType: mediaType,
displayImage: displayImage,
scaledWidth: scaledWidth,
scaledHeight: scaledHeight,
scale: scale,
videoURL: videoURL,
imageURL: imageURL,
blindGenerate: blindGenerate,
onBackTap: {
// BlindOutcomeView
if mediaType == .video, !videoURL.isEmpty, let url = URL(string: videoURL) {
Router.shared.navigate(to: .blindOutcome(media: .video(url, nil), time: blindGenerate?.videoGenerateTime ?? "hhsdshjsjdhn", description:blindGenerate?.description ?? "informationinformationinformationinformationinformationinformation"))
} else if mediaType == .image, let image = displayImage {
Router.shared.navigate(to: .blindOutcome(media: .image(image), time: blindGenerate?.videoGenerateTime ?? "hhsdshjsjdhn", description:blindGenerate?.description ?? "informationinformationinformationinformationinformationinformation"))
}
}
)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.animation(.easeInOut(duration: 1.0), value: scale)
.ignoresSafeArea()
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
withAnimation(.spring(response: 2.5, dampingFraction: 0.6, blendDuration: 1.0)) {
self.scale = 1.0
}
}
}
} else {
// Original content
VStack {
VStack(spacing: 20) {
if mediaType == .all {
BlindBoxNavigationBar(
memberProfile: memberProfile,
showLogin: showLogin,
showUserProfile: showUserProfile
)
}
//
VStack(alignment: .leading, spacing: 4) {
Text("Hi! Click And")
Text("Open Your First Box~")
}
.font(Typography.font(for: .smallLargeTitle))
.fontWeight(.bold)
.foregroundColor(Color.themeTextMessageMain)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal)
.opacity(showScalingOverlay ? 0 : 1)
.offset(y: showScalingOverlay ? -UIScreen.main.bounds.height * 0.2 : 0)
.animation(.easeInOut(duration: 0.5), value: showScalingOverlay)
//
BlindBoxAnimationView(
mediaType: mediaType,
animationPhase: animationPhase,
blindCount: blindCount,
blindGenerate: blindGenerate,
scale: scale,
showScalingOverlay: showScalingOverlay,
showMedia: showMedia,
onBoxTap: {
print("点击了盲盒")
withAnimation {
animationPhase = .opening
}
}
)
//
BlindBoxControls(
mediaType: mediaType,
animationPhase: animationPhase,
countdown: countdown,
onButtonTap: {
if animationPhase == .ready {
//
//
Router.shared.navigate(to: .subscribe)
} else {
showUserProfile()
}
},
onCountdownStart: startCountdown
)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.themeTextWhiteSecondary)
.offset(x: showModal ? UIScreen.main.bounds.width * 0.8 : 0)
.animation(.spring(response: 0.6, dampingFraction: 0.8), value: showModal)
.edgesIgnoringSafeArea(.all)
}
//
SlideInModal(
isPresented: $showModal,
onDismiss: hideUserProfile
) {
UserProfileModal(
showModal: $showModal,
showSettings: $showSettings,
isMember: $isMember,
memberDate: $memberDate
)
}
.offset(x: showSettings ? UIScreen.main.bounds.width : 0)
.animation(.spring(response: 0.6, dampingFraction: 0.8), value: showSettings)
//
ZStack {
if showSettings {
Color.black.opacity(0.3)
.edgesIgnoringSafeArea(.all)
.onTapGesture(perform: hideSettings)
.transition(.opacity)
}
if showSettings {
SettingsView(isPresented: $showSettings)
.transition(.move(edge: .leading))
.zIndex(1)
}
}
.animation(.spring(response: 0.6, dampingFraction: 0.8), value: showSettings)
}
}
.navigationBarBackButtonHidden(true)
}
///
private func showUserProfile() {
withAnimation(.spring(response: 0.6, dampingFraction: 0.8)) {
// print(": \(login.count)")
// for (index, item) in login.enumerated() {
// print(" \(index + 1): =\(item.email), =\(item.name)")
// }
print("当前登录记录:")
for (index, item) in login.enumerated() {
print("记录 \(index + 1): 邮箱=\(item.email), 姓名=\(item.name)")
}
showModal.toggle()
}
}
///
private func hideUserProfile() {
withAnimation(.spring(response: 0.6, dampingFraction: 0.8)) {
showModal = false
}
}
///
private func hideSettings() {
withAnimation(.spring(response: 0.6, dampingFraction: 0.8)) {
showSettings = false
} }
.environmentObject(router)
} }
} }
// MARK: -
#Preview { #Preview {
BlindBoxView(mediaType: .video) ContentView()
} }

View File

@ -1,105 +0,0 @@
import SwiftUI
struct AvatarBoxView: View {
@Environment(\.dismiss) private var dismiss
@EnvironmentObject private var router: Router
@State private var isAnimating = false
var body: some View {
ZStack {
// Background color
Color.white
.ignoresSafeArea()
VStack(spacing: 0) {
// Navigation Bar
HStack {
Button(action: {
dismiss()
}) {
Image(systemName: "chevron.left")
.font(.system(size: 17, weight: .medium))
.foregroundColor(.black)
.padding()
}
Spacer()
Text("动画页面")
.font(.headline)
.foregroundColor(.black)
Spacer()
// Invisible spacer to center the title
Color.clear
.frame(width: 44, height: 44)
}
.frame(height: 44)
.background(Color.white)
Spacer()
// Animated Content
ZStack {
// Pulsing circle animation
Circle()
.fill(Color.blue.opacity(0.2))
.frame(width: 200, height: 200)
.scaleEffect(isAnimating ? 1.5 : 1.0)
.opacity(isAnimating ? 0.5 : 1.0)
.animation(
Animation.easeInOut(duration: 1.5)
.repeatForever(autoreverses: true),
value: isAnimating
)
// Center icon
Image(systemName: "sparkles")
.font(.system(size: 60))
.foregroundColor(.blue)
.rotationEffect(.degrees(isAnimating ? 360 : 0))
.animation(
Animation.linear(duration: 8)
.repeatForever(autoreverses: false),
value: isAnimating
)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
Spacer()
// Bottom Button
Button(action: {
router.navigate(to: .feedbackView)
}) {
Text("Continue")
.font(.headline)
.foregroundColor(.themeTextMessageMain)
.frame(maxWidth: .infinity)
.frame(height: 56)
.background(Color.themePrimary)
.cornerRadius(25)
.padding(.horizontal, 24)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
.navigationBarBackButtonHidden(true)
.navigationBarHidden(true)
.onAppear {
isAnimating = true
}
}
}
// MARK: - Preview
struct AvatarBoxView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
AvatarBoxView()
.environmentObject(Router.shared)
}
.navigationViewStyle(StackNavigationViewStyle())
}
}

View File

@ -1,301 +0,0 @@
import SwiftUI
struct FilmStripView: View {
@State private var animate = false
// 使SF Symbols
private let symbolNames = [
"photo.fill", "heart.fill", "star.fill", "bookmark.fill",
"flag.fill", "bell.fill", "tag.fill", "paperplane.fill"
]
private let targetIndices = [2, 5, 3] //
var body: some View {
ZStack {
Color.black.edgesIgnoringSafeArea(.all)
//
FilmStrip(
symbols: symbolNames,
targetIndex: targetIndices[0],
offset: 0,
stripColor: .red
)
.rotationEffect(.degrees(5))
.zIndex(1)
FilmStrip(
symbols: symbolNames,
targetIndex: targetIndices[1],
offset: 0.3,
stripColor: .blue
)
.rotationEffect(.degrees(-3))
.zIndex(2)
FilmStrip(
symbols: symbolNames,
targetIndex: targetIndices[2],
offset: 0.6,
stripColor: .green
)
.rotationEffect(.degrees(2))
.zIndex(3)
}
.onAppear {
withAnimation(
.timingCurve(0.2, 0.1, 0.8, 0.9, duration: 4.0)
) {
animate = true
}
}
}
}
//
struct FilmStrip: View {
let symbols: [String]
let targetIndex: Int
let offset: Double
let stripColor: Color
@State private var animate = false
var body: some View {
GeometryReader { geometry in
let itemWidth: CGFloat = 100
let spacing: CGFloat = 8
let totalWidth = itemWidth * CGFloat(symbols.count) + spacing * CGFloat(symbols.count - 1)
//
RoundedRectangle(cornerRadius: 10)
.fill(stripColor.opacity(0.8))
.frame(height: 160)
.overlay(
// 齿
HStack(spacing: spacing) {
ForEach(0..<symbols.count * 3, id: \.self) { index in
Circle()
.fill(Color.black)
.frame(width: 12, height: 12)
.offset(y: -75)
}
}
.frame(width: totalWidth * 3),
alignment: .leading
)
.overlay(
//
HStack(spacing: spacing) {
ForEach(0..<symbols.count * 3, id: \.self) { index in
let actualIndex = index % symbols.count
ZStack {
RoundedRectangle(cornerRadius: 6)
.fill(Color.white)
.frame(width: itemWidth - 10, height: 100)
Image(systemName: symbols[actualIndex])
.font(.system(size: 30))
.foregroundColor(stripColor)
.shadow(radius: 2)
}
}
}
.offset(x: animate ? -CGFloat(targetIndex) * (itemWidth + spacing) - totalWidth : 0)
.frame(width: totalWidth * 3),
alignment: .leading
)
}
.frame(height: 180)
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + offset) {
withAnimation(
.timingCurve(0.2, 0.1, 0.8, 0.9, duration: 3.5)
) {
animate = true
}
}
}
}
}
//
struct EnhancedFilmStrip: View {
let symbols: [String]
let targetIndex: Int
let offset: Double
let stripColor: Color
@State private var animate = false
var body: some View {
GeometryReader { geometry in
let itemWidth: CGFloat = 110
let spacing: CGFloat = 10
let totalWidth = itemWidth * CGFloat(symbols.count) + spacing * CGFloat(symbols.count - 1)
ZStack {
//
RoundedRectangle(cornerRadius: 12)
.fill(Color.black.opacity(0.3))
.frame(height: 170)
.offset(y: 5)
.blur(radius: 3)
//
RoundedRectangle(cornerRadius: 12)
.fill(stripColor)
.frame(height: 170)
.overlay(
// 齿
HStack(spacing: spacing) {
ForEach(0..<symbols.count * 3, id: \.self) { index in
VStack {
Circle()
.fill(Color.black)
.frame(width: 14, height: 14)
.padding(.top, 8)
Spacer()
Circle()
.fill(Color.black)
.frame(width: 14, height: 14)
.padding(.bottom, 8)
}
.frame(height: 170)
}
}
.frame(width: totalWidth * 3),
alignment: .leading
)
//
HStack(spacing: spacing) {
ForEach(0..<symbols.count * 3, id: \.self) { index in
let actualIndex = index % symbols.count
ZStack {
RoundedRectangle(cornerRadius: 8)
.fill(Color.white)
.frame(width: itemWidth - 15, height: 110)
.shadow(color: .black.opacity(0.2), radius: 3, x: 0, y: 2)
VStack {
Image(systemName: symbols[actualIndex])
.font(.system(size: 32, weight: .bold))
.foregroundColor(stripColor)
Text("\(actualIndex + 1)")
.font(.caption)
.foregroundColor(.gray)
}
}
}
}
.offset(x: animate ? -CGFloat(targetIndex) * (itemWidth + spacing) - totalWidth : 0)
.frame(width: totalWidth * 3)
}
}
.frame(height: 180)
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + offset) {
withAnimation(
.timingCurve(0.2, 0.1, 0.8, 0.9, duration: 3.5)
) {
animate = true
}
}
}
}
}
//
struct FilmStripView_Previews: PreviewProvider {
static var previews: some View {
FilmStripView()
}
}
// 使
struct EnhancedFilmStripView: View {
@State private var animate = false
private let symbolNames = [
"camera.fill", "film.fill", "photo.fill", "heart.fill",
"star.fill", "bookmark.fill", "flag.fill", "bell.fill"
]
private let targetIndices = [2, 5, 3]
var body: some View {
ZStack {
LinearGradient(
gradient: Gradient(colors: [Color.blue.opacity(0.8), Color.purple.opacity(0.8)]),
startPoint: .topLeading,
endPoint: .bottomTrailing
)
.edgesIgnoringSafeArea(.all)
VStack(spacing: 30) {
Text("胶片动效展示")
.font(.title)
.fontWeight(.bold)
.foregroundColor(.white)
.padding(.top)
EnhancedFilmStrip(
symbols: symbolNames,
targetIndex: targetIndices[0],
offset: 0,
stripColor: .red
)
.rotationEffect(.degrees(4))
EnhancedFilmStrip(
symbols: symbolNames,
targetIndex: targetIndices[1],
offset: 0.4,
stripColor: .blue
)
.rotationEffect(.degrees(-2))
EnhancedFilmStrip(
symbols: symbolNames,
targetIndex: targetIndices[2],
offset: 0.8,
stripColor: .green
)
.rotationEffect(.degrees(3))
Button("重新播放") {
restartAnimation()
}
.padding()
.background(Color.white)
.foregroundColor(.blue)
.cornerRadius(10)
.padding()
}
}
.onAppear {
startAnimation()
}
}
private func startAnimation() {
withAnimation(
.timingCurve(0.2, 0.1, 0.8, 0.9, duration: 4.0)
) {
animate = true
}
}
private func restartAnimation() {
animate = false
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
startAnimation()
}
}
}
//
struct EnhancedFilmStripView_Previews: PreviewProvider {
static var previews: some View {
EnhancedFilmStripView()
}
}

View File

@ -1,253 +0,0 @@
import SwiftUI
struct ReplayableFilmReelAnimation: View {
//
@State private var animationProgress: CGFloat = 0
@State private var isCatching: Bool = false
@State private var isDisappearing: Bool = false
@State private var showReplayButton: Bool = false
// 16
private let reelImages: [[String]] = [
(0..<16).map { "film1-\($0+1)" }, //
(0..<16).map { "film2-\($0+1)" }, //
(0..<16).map { "film3-\($0+1)" } //
]
//
private let topTiltAngle: Double = -7 //
private let bottomTiltAngle: Double = 7 //
//
private let targetImageIndex: Int = 8
var body: some View {
ZStack {
//
Color(red: 0.08, green: 0.08, blue: 0.08).edgesIgnoringSafeArea(.all)
// -
ZStack {
//
FilmReelView1(images: reelImages[0])
.rotationEffect(Angle(degrees: topTiltAngle))
.offset(x: calculateTopOffset(), y: -200)
.opacity(isDisappearing ? 0 : 1)
.zIndex(1)
//
FilmReelView1(images: reelImages[1])
.offset(x: calculateMiddleOffset(), y: 0)
.scaleEffect(isCatching ? 1.03 : 1.0)
.opacity(isDisappearing ? 0 : 1)
.zIndex(2)
//
FilmReelView1(images: reelImages[2])
.rotationEffect(Angle(degrees: bottomTiltAngle))
.offset(x: calculateBottomOffset(), y: 200)
.opacity(isDisappearing ? 0 : 1)
.zIndex(1)
//
if isDisappearing {
Image(reelImages[1][targetImageIndex])
.resizable()
.scaledToFit()
.frame(maxWidth: .infinity, maxHeight: .infinity)
.padding()
.transition(.opacity.combined(with: .scale))
.zIndex(3)
}
}
//
if showReplayButton {
Button(action: resetAndReplay) {
ZStack {
Circle()
.fill(Color.black.opacity(0.7))
.frame(width: 60, height: 60)
.shadow(radius: 10)
Image(systemName: "arrow.counterclockwise")
.foregroundColor(.white)
.font(.system(size: 24))
}
}
.position(x: UIScreen.main.bounds.width - 40, y: 40)
.transition(.opacity.combined(with: .scale))
.zIndex(4)
}
}
.onAppear {
startAnimation()
}
}
//
private func resetAndReplay() {
withAnimation(.easeInOut(duration: 0.5)) {
showReplayButton = false
isDisappearing = false
isCatching = false
animationProgress = 0
}
//
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
startAnimation()
}
}
//
private func calculateTopOffset() -> CGFloat {
let baseDistance: CGFloat = 1000
let speedFactor: CGFloat = 1.0
return baseDistance * speedFactor * progressCurve()
}
//
private func calculateMiddleOffset() -> CGFloat {
let baseDistance: CGFloat = -1100
let speedFactor: CGFloat = 1.05
return baseDistance * speedFactor * progressCurve()
}
//
private func calculateBottomOffset() -> CGFloat {
let baseDistance: CGFloat = 1000
let speedFactor: CGFloat = 0.95
return baseDistance * speedFactor * progressCurve()
}
// 线
private func progressCurve() -> CGFloat {
if animationProgress < 0.6 {
//
return easeInQuad(animationProgress / 0.6) * 0.7
} else if animationProgress < 0.85 {
//
return 0.7 + easeOutQuad((animationProgress - 0.6) / 0.25) * 0.25
} else {
//
let t = (animationProgress - 0.85) / 0.15
return 0.95 + t * 0.05
}
}
// 线
private func easeInQuad(_ t: CGFloat) -> CGFloat {
return t * t
}
// 线
private func easeOutQuad(_ t: CGFloat) -> CGFloat {
return t * (2 - t)
}
//
private func startAnimation() {
//
withAnimation(.easeIn(duration: 3.5)) {
animationProgress = 0.6
}
//
DispatchQueue.main.asyncAfter(deadline: .now() + 3.5) {
withAnimation(.linear(duration: 2.5)) {
animationProgress = 0.85
}
//
DispatchQueue.main.asyncAfter(deadline: .now() + 2.5) {
withAnimation(.easeOut(duration: 1.8)) {
animationProgress = 1.0
isCatching = true
}
//
DispatchQueue.main.asyncAfter(deadline: .now() + 1.8) {
withAnimation(.easeInOut(duration: 0.7)) {
isDisappearing = true
}
//
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
withAnimation(.easeInOut(duration: 0.3)) {
showReplayButton = true
}
}
}
}
}
}
}
//
struct FilmReelView1: View {
let images: [String]
var body: some View {
HStack(spacing: 10) {
ForEach(images.indices, id: \.self) { index in
ZStack {
//
RoundedRectangle(cornerRadius: 4)
.stroke(Color.gray, lineWidth: 2)
.background(Color(red: 0.15, green: 0.15, blue: 0.15))
//
Rectangle()
.fill(
LinearGradient(
gradient: Gradient(colors: [.blue, .indigo]),
startPoint: .topLeading,
endPoint: .bottomTrailing
)
)
.opacity(0.9)
.cornerRadius(2)
.padding(2)
//
Text("\(images[index])")
.foregroundColor(.white)
.font(.caption2)
}
.frame(width: 90, height: 130)
//
.overlay(
HStack {
VStack(spacing: 6) {
ForEach(0..<6) { _ in
Circle()
.frame(width: 6, height: 6)
.foregroundColor(.gray)
}
}
Spacer()
VStack(spacing: 6) {
ForEach(0..<6) { _ in
Circle()
.frame(width: 6, height: 6)
.foregroundColor(.gray)
}
}
}
)
}
}
}
}
//
struct ReplayableFilmReelAnimation_Previews: PreviewProvider {
static var previews: some View {
ReplayableFilmReelAnimation()
}
}

View File

@ -1,226 +0,0 @@
import SwiftUI
struct FilmAnimation1: View {
//
private let deviceWidth = UIScreen.main.bounds.width
private let deviceHeight = UIScreen.main.bounds.height
//
@State private var animationProgress: CGFloat = 0.0 // 0-1
@State private var isAnimating: Bool = false
@State private var animationComplete: Bool = false
//
private let reelImages: [[String]] = [
(0..<150).map { "film1-\($0+1)" }, //
(0..<180).map { "film2-\($0+1)" }, //
(0..<150).map { "film3-\($0+1)" } //
]
//
private let frameWidth: CGFloat = 90
private let frameHeight: CGFloat = 130
private let frameSpacing: CGFloat = 10
private let totalDistance: CGFloat = 2000 //
//
private let accelerationDuration: Double = 5.0 // 0-5s
private let constantSpeedDuration: Double = 6.0 // +5-11s
private var totalDuration: Double { accelerationDuration + constantSpeedDuration }
private var scaleStartProgress: CGFloat { accelerationDuration / totalDuration }
private let finalScale: CGFloat = 3.0 //
//
private let symmetricTiltAngle: Double = 8 //
private let verticalOffset: CGFloat = 140 //
private let initialMiddleY: CGFloat = 50 //
//
private let horizontalOffset: CGFloat = 30
var body: some View {
ZStack {
//
Color(red: 0.08, green: 0.08, blue: 0.08)
.edgesIgnoringSafeArea(.all)
//
FilmReelView3(images: reelImages[0])
.rotationEffect(Angle(degrees: -symmetricTiltAngle))
.offset(x: topReelPosition - horizontalOffset, y: -verticalOffset) //
.opacity(upperLowerOpacity)
.zIndex(1)
//
FilmReelView3(images: reelImages[2])
.rotationEffect(Angle(degrees: symmetricTiltAngle))
.offset(x: bottomReelPosition + horizontalOffset, y: verticalOffset) //
.opacity(upperLowerOpacity)
.zIndex(1)
//
FilmReelView3(images: reelImages[1])
.offset(x: middleReelPosition, y: middleYPosition)
.scaleEffect(currentScale)
.position(centerPosition)
.zIndex(2)
.edgesIgnoringSafeArea(.all)
}
.onAppear {
startAnimation()
}
}
// MARK: -
private func startAnimation() {
guard !isAnimating && !animationComplete else { return }
isAnimating = true
withAnimation(Animation.timingCurve(0.2, 0.0, 0.8, 1.0, duration: totalDuration)) {
animationProgress = 1.0
}
DispatchQueue.main.asyncAfter(deadline: .now() + totalDuration) {
isAnimating = false
animationComplete = true
}
}
// MARK: -
private var currentScale: CGFloat {
guard animationProgress >= scaleStartProgress else {
return 1.0
}
let scalePhaseProgress = (animationProgress - scaleStartProgress) / (1.0 - scaleStartProgress)
return 1.0 + (finalScale - 1.0) * scalePhaseProgress
}
// Y
private var middleYPosition: CGFloat {
if animationProgress < scaleStartProgress {
return initialMiddleY - (initialMiddleY * (animationProgress / scaleStartProgress))
} else {
return 0 // 5s
}
}
private var upperLowerOpacity: Double {
if animationProgress < scaleStartProgress {
return 0.8
} else {
let fadeProgress = (animationProgress - scaleStartProgress) / (1.0 - scaleStartProgress)
return 0.8 * (1.0 - fadeProgress)
}
}
private var centerPosition: CGPoint {
CGPoint(x: deviceWidth / 2, y: deviceHeight / 2)
}
// MARK: -
private var motionProgress: CGFloat {
if animationProgress < scaleStartProgress {
let t = animationProgress / scaleStartProgress
return t * t //
} else {
return 1.0 + (animationProgress - scaleStartProgress) *
(scaleStartProgress / (1.0 - scaleStartProgress))
}
}
//
private var topReelPosition: CGFloat {
totalDistance * 0.9 * motionProgress
}
//
private var middleReelPosition: CGFloat {
-totalDistance * 1.2 * motionProgress
}
//
private var bottomReelPosition: CGFloat {
totalDistance * 0.9 * motionProgress //
}
}
// MARK: -
struct FilmReelView3: View {
let images: [String]
var body: some View {
HStack(spacing: 10) {
ForEach(images.indices, id: \.self) { index in
FilmFrameView3(imageName: images[index])
}
}
}
}
struct FilmFrameView3: View {
let imageName: String
var body: some View {
ZStack {
//
RoundedRectangle(cornerRadius: 4)
.stroke(Color.gray, lineWidth: 2)
.background(Color(red: 0.15, green: 0.15, blue: 0.15))
//
Rectangle()
.fill(gradientColor)
.cornerRadius(2)
.padding(2)
//
Text(imageName)
.foregroundColor(.white)
.font(.caption2)
}
.frame(width: 90, height: 130)
//
.overlay(
HStack {
VStack(spacing: 6) {
ForEach(0..<6) { _ in
Circle()
.frame(width: 6, height: 6)
.foregroundColor(.gray)
}
}
Spacer()
VStack(spacing: 6) {
ForEach(0..<6) { _ in
Circle()
.frame(width: 6, height: 6)
.foregroundColor(.gray)
}
}
}
)
}
private var gradientColor: LinearGradient {
if imageName.hasPrefix("film1") {
return LinearGradient(gradient: Gradient(colors: [.blue, .indigo]), startPoint: .topLeading, endPoint: .bottomTrailing)
} else if imageName.hasPrefix("film2") {
return LinearGradient(gradient: Gradient(colors: [.yellow, .orange]), startPoint: .topLeading, endPoint: .bottomTrailing)
} else {
return LinearGradient(gradient: Gradient(colors: [.teal, .cyan]), startPoint: .topLeading, endPoint: .bottomTrailing)
}
}
}
//
struct FilmAnimation_Previews3: PreviewProvider {
static var previews: some View {
FilmAnimation1()
}
}

View File

@ -1,140 +0,0 @@
import SwiftUI
// MARK: -
struct FilmStripBlindBoxView: View {
@State private var isAnimating = false
@State private var revealCenter = false
// 使 SF Symbols
let boxContents = ["popcorn", "star", "music.note"]
var body: some View {
GeometryReader { geometry in
let width = geometry.size.width
ZStack {
//
BlindBoxFrame(symbol: boxContents[0])
.offset(x: isAnimating ? -width / 4 : -width)
.opacity(isAnimating ? 1 : 0)
//
BlindBoxFrame(symbol: boxContents[1])
.scaleEffect(revealCenter ? 1.6 : 1)
.offset(x: isAnimating ? 0 : width)
.opacity(isAnimating ? 1 : 0)
//
BlindBoxFrame(symbol: boxContents[2])
.offset(x: isAnimating ? width / 4 : width * 1.5)
.opacity(isAnimating ? 1 : 0)
}
.onAppear {
//
withAnimation(.easeOut(duration: 1.0)) {
isAnimating = true
}
//
DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) {
withAnimation(
.interpolatingSpring(stiffness: 80, damping: 12).delay(0.3)
) {
revealCenter = true
}
}
}
}
.frame(height: 140)
.padding()
.background(Color.black.opacity(0.05))
}
}
// MARK: - + + SF Symbol
struct BlindBoxFrame: View {
let symbol: String
var body: some View {
ZStack {
// +
FilmBorder()
// SF Symbol
Image(systemName: symbol)
.resizable()
.scaledToFit()
.foregroundColor(.white.opacity(0.85))
.frame(width: 60, height: 60)
}
.frame(width: 120, height: 120)
}
}
// MARK: - #FFB645 +
struct FilmBorder: View {
var body: some View {
Canvas { context, size in
let w = size.width
let h = size.height
// FFB645
let bgColor = Color(hex: 0xFFB645)
context.fill(Path(CGRect(origin: .zero, size: size)), with: .color(bgColor))
//
let holeRadius: CGFloat = 3.5
let margin: CGFloat = 12
let holeYOffset: CGFloat = h * 0.25
// 3
for i in 0..<3 {
let y = CGFloat(i + 1) * (h / 4)
context.fill(
Path(ellipseIn: CGRect(
x: margin - holeRadius * 2,
y: y - holeRadius,
width: holeRadius * 2,
height: holeRadius * 2
)),
with: .color(.black)
)
}
// 3
for i in 0..<3 {
let y = CGFloat(i + 1) * (h / 4)
context.fill(
Path(ellipseIn: CGRect(
x: w - margin,
y: y - holeRadius,
width: holeRadius * 2,
height: holeRadius * 2
)),
with: .color(.black)
)
}
}
}
}
// MARK: - Color HEX
extension Color {
init(hex: UInt) {
self.init(
.sRGB,
red: Double((hex >> 16) & 0xff) / 255,
green: Double((hex >> 8) & 0xff) / 255,
blue: Double(hex & 0xff) / 255,
opacity: 1.0
)
}
}
// MARK: -
struct FilmStripBlindBoxView_Previews: PreviewProvider {
static var previews: some View {
FilmStripBlindBoxView()
.preferredColorScheme(.dark)
}
}

View File

@ -1,222 +0,0 @@
import SwiftUI
struct FilmAnimation5: View {
//
private let deviceWidth = UIScreen.main.bounds.width
private let deviceHeight = UIScreen.main.bounds.height
//
@State private var animationProgress: CGFloat = 0.0 // 0-1
@State private var isAnimating: Bool = false
@State private var animationComplete: Bool = false
//
private let reelImages: [[String]] = [
(0..<150).map { "film1-\($0+1)" }, //
(0..<180).map { "film2-\($0+1)" }, //
(0..<150).map { "film3-\($0+1)" } //
]
//
private let frameWidth: CGFloat = 90
private let frameHeight: CGFloat = 130
private let totalDistance: CGFloat = 1800 //
//
private let accelerationDuration: Double = 5.0 // 0-5s
private let constantSpeedDuration: Double = 1.0 // 5-6s
private let scaleDuration: Double = 2.0 // 6-8s
private var totalDuration: Double { accelerationDuration + constantSpeedDuration + scaleDuration }
//
private var accelerationEnd: CGFloat { accelerationDuration / totalDuration }
private var constantSpeedEnd: CGFloat { (accelerationDuration + constantSpeedDuration) / totalDuration }
//
private let symmetricTiltAngle: Double = 10 //
private let verticalOffset: CGFloat = 120 //
private let finalScale: CGFloat = 4.0 //
var body: some View {
ZStack {
//
Color(red: 0.08, green: 0.08, blue: 0.08)
.edgesIgnoringSafeArea(.all)
//
FilmReelView5(images: reelImages[0])
.rotationEffect(Angle(degrees: -symmetricTiltAngle))
.offset(x: topReelPosition, y: -verticalOffset)
.scaleEffect(currentScale)
.opacity(upperLowerOpacity)
.zIndex(2)
//
FilmReelView5(images: reelImages[2])
.rotationEffect(Angle(degrees: symmetricTiltAngle))
.offset(x: bottomReelPosition, y: verticalOffset)
.scaleEffect(currentScale)
.opacity(upperLowerOpacity)
.zIndex(2)
//
FilmReelView5(images: reelImages[1])
.offset(x: middleReelPosition, y: 0)
.scaleEffect(currentScale)
.opacity(1.0) //
.zIndex(1)
.edgesIgnoringSafeArea(.all)
}
.onAppear {
startAnimation()
}
}
// MARK: -
private func startAnimation() {
guard !isAnimating && !animationComplete else { return }
isAnimating = true
// 线
withAnimation(Animation.timingCurve(0.3, 0.0, 0.7, 1.0, duration: totalDuration)) {
animationProgress = 1.0
}
//
DispatchQueue.main.asyncAfter(deadline: .now() + totalDuration) {
isAnimating = false
animationComplete = true
}
}
// MARK: -
// 6s
private var currentScale: CGFloat {
guard animationProgress >= constantSpeedEnd else {
return 1.0 // 6s
}
// 0-1
let scalePhaseProgress = (animationProgress - constantSpeedEnd) / (1.0 - constantSpeedEnd)
return 1.0 + (finalScale - 1.0) * scalePhaseProgress
}
//
private var upperLowerOpacity: Double {
guard animationProgress >= constantSpeedEnd else {
return 0.8 // 6s
}
//
let fadeProgress = (animationProgress - constantSpeedEnd) / (1.0 - constantSpeedEnd)
return 0.8 * (1.0 - fadeProgress)
}
// MARK: -
private var motionProgress: CGFloat {
if animationProgress < accelerationEnd {
// 0-5s线
let t = animationProgress / accelerationEnd
return t * t
} else {
// 5s
return 1.0 + (animationProgress - accelerationEnd) *
(accelerationEnd / (1.0 - accelerationEnd))
}
}
//
private var topReelPosition: CGFloat {
totalDistance * 0.8 * motionProgress
}
//
private var middleReelPosition: CGFloat {
-totalDistance * 0.8 * motionProgress //
}
//
private var bottomReelPosition: CGFloat {
totalDistance * 0.8 * motionProgress //
}
}
// MARK: -
struct FilmReelView5: View {
let images: [String]
var body: some View {
HStack(spacing: 10) {
ForEach(images.indices, id: \.self) { index in
FilmFrameView5(imageName: images[index])
}
}
}
}
struct FilmFrameView5: View {
let imageName: String
var body: some View {
ZStack {
//
RoundedRectangle(cornerRadius: 4)
.stroke(Color.gray, lineWidth: 2)
.background(Color(red: 0.15, green: 0.15, blue: 0.15))
//
Rectangle()
.fill(gradientColor)
.cornerRadius(2)
.padding(2)
//
Text(imageName)
.foregroundColor(.white)
.font(.caption2)
}
.frame(width: 90, height: 130)
//
.overlay(
HStack {
VStack(spacing: 6) {
ForEach(0..<6) { _ in
Circle()
.frame(width: 6, height: 6)
.foregroundColor(.gray)
}
}
Spacer()
VStack(spacing: 6) {
ForEach(0..<6) { _ in
Circle()
.frame(width: 6, height: 6)
.foregroundColor(.gray)
}
}
}
)
}
private var gradientColor: LinearGradient {
if imageName.hasPrefix("film1") {
return LinearGradient(gradient: Gradient(colors: [.blue, .indigo]), startPoint: .topLeading, endPoint: .bottomTrailing)
} else if imageName.hasPrefix("film2") {
return LinearGradient(gradient: Gradient(colors: [.yellow, .orange]), startPoint: .topLeading, endPoint: .bottomTrailing)
} else {
return LinearGradient(gradient: Gradient(colors: [.teal, .cyan]), startPoint: .topLeading, endPoint: .bottomTrailing)
}
}
}
//
struct FilmAnimation_Previews5: PreviewProvider {
static var previews: some View {
FilmAnimation5()
}
}

View File

@ -1,250 +0,0 @@
import SwiftUI
struct FilmAnimation: View {
//
private let deviceWidth = UIScreen.main.bounds.width
private let deviceHeight = UIScreen.main.bounds.height
//
@State private var animationProgress: CGFloat = 0.0 // 0-1
@State private var isAnimating: Bool = false
@State private var animationComplete: Bool = false
//
private let reelImages: [[String]] = [
(0..<300).map { "film1-\($0+1)" }, //
(0..<350).map { "film2-\($0+1)" }, //
(0..<300).map { "film3-\($0+1)" } //
]
//
private let frameWidth: CGFloat = 90
private let frameHeight: CGFloat = 130
private let frameSpacing: CGFloat = 12
//
private let accelerationDuration: Double = 5.0 // 0-5s
private let constantSpeedDuration: Double = 1.0 // 5-6s
private let scaleStartDuration: Double = 1.0 // 6-7s
private let scaleFinishDuration: Double = 1.0 // 7-8s
private var totalDuration: Double {
accelerationDuration + constantSpeedDuration + scaleStartDuration + scaleFinishDuration
}
//
private var accelerationEnd: CGFloat { accelerationDuration / totalDuration }
private var constantSpeedEnd: CGFloat { (accelerationDuration + constantSpeedDuration) / totalDuration }
private var scaleStartEnd: CGFloat {
(accelerationDuration + constantSpeedDuration + scaleStartDuration) / totalDuration
}
//
private let tiltAngle: Double = 10 //
private let upperTilt: Double = -10 //
private let lowerTilt: Double = 10 //
private let verticalSpacing: CGFloat = 200 //
private let finalScale: CGFloat = 4.5
//
private let maxTiltedReelMovement: CGFloat = 3500 //
private let maxMiddleReelMovement: CGFloat = -3000 //
var body: some View {
//
Color(red: 0.08, green: 0.08, blue: 0.08)
.edgesIgnoringSafeArea(.all)
.overlay(
ZStack {
//
if showTiltedReels {
FilmReelView(images: reelImages[0])
.rotationEffect(Angle(degrees: upperTilt)) //
.offset(x: upperReelXPosition, y: -verticalSpacing/2)
.scaleEffect(tiltedScale)
.opacity(tiltedOpacity)
.zIndex(1)
}
//
if showTiltedReels {
FilmReelView(images: reelImages[2])
.rotationEffect(Angle(degrees: lowerTilt)) //
.offset(x: lowerReelXPosition, y: verticalSpacing/2)
.scaleEffect(tiltedScale)
.opacity(tiltedOpacity)
.zIndex(1)
}
//
FilmReelView(images: reelImages[1])
.offset(x: middleReelXPosition, y: 0)
.scaleEffect(middleScale)
.opacity(1.0)
.zIndex(2)
.edgesIgnoringSafeArea(.all)
}
)
.onAppear {
startAnimation()
}
}
// MARK: -
private func startAnimation() {
guard !isAnimating && !animationComplete else { return }
isAnimating = true
withAnimation(Animation.easeInOut(duration: totalDuration)) {
animationProgress = 1.0
}
DispatchQueue.main.asyncAfter(deadline: .now() + totalDuration) {
isAnimating = false
animationComplete = true
}
}
// MARK: -
// X
private var upperReelXPosition: CGFloat {
let startPosition: CGFloat = -deviceWidth * 1.2 //
return startPosition + (maxTiltedReelMovement * movementProgress)
}
// X
private var lowerReelXPosition: CGFloat {
let startPosition: CGFloat = -deviceWidth * 0.8 //
return startPosition + (maxTiltedReelMovement * movementProgress)
}
// X
private var middleReelXPosition: CGFloat {
let startPosition: CGFloat = deviceWidth * 0.3
return startPosition + (maxMiddleReelMovement * movementProgress)
}
// 0-1
private var movementProgress: CGFloat {
if animationProgress < constantSpeedEnd {
return animationProgress / constantSpeedEnd
} else {
return 1.0 // 6
}
}
// MARK: -
//
private var middleScale: CGFloat {
guard animationProgress >= constantSpeedEnd else {
return 1.0
}
let scalePhaseProgress = (animationProgress - constantSpeedEnd) / (1.0 - constantSpeedEnd)
return 1.0 + (finalScale - 1.0) * scalePhaseProgress
}
//
private var tiltedScale: CGFloat {
guard animationProgress >= constantSpeedEnd, animationProgress < scaleStartEnd else {
return 1.0
}
let scalePhaseProgress = (animationProgress - constantSpeedEnd) / (scaleStartEnd - constantSpeedEnd)
return 1.0 + (finalScale * 0.6 - 1.0) * scalePhaseProgress
}
//
private var tiltedOpacity: Double {
guard animationProgress >= constantSpeedEnd, animationProgress < scaleStartEnd else {
return 0.8
}
let fadeProgress = (animationProgress - constantSpeedEnd) / (scaleStartEnd - constantSpeedEnd)
return 0.8 * (1.0 - fadeProgress)
}
//
private var showTiltedReels: Bool {
animationProgress < scaleStartEnd
}
}
// MARK: -
struct FilmReelView: View {
let images: [String]
var body: some View {
HStack(spacing: 12) {
ForEach(images.indices, id: \.self) { index in
FilmFrameView(imageName: images[index])
}
}
}
}
struct FilmFrameView: View {
let imageName: String
var body: some View {
ZStack {
//
RoundedRectangle(cornerRadius: 4)
.stroke(Color.gray, lineWidth: 2)
.background(Color(red: 0.15, green: 0.15, blue: 0.15))
//
Rectangle()
.fill(gradientColor)
.cornerRadius(2)
.padding(2)
//
Text(imageName)
.foregroundColor(.white)
.font(.caption2)
}
.frame(width: 90, height: 130)
//
.overlay(
HStack {
VStack(spacing: 6) {
ForEach(0..<6) { _ in
Circle()
.frame(width: 6, height: 6)
.foregroundColor(.gray)
}
}
Spacer()
VStack(spacing: 6) {
ForEach(0..<6) { _ in
Circle()
.frame(width: 6, height: 6)
.foregroundColor(.gray)
}
}
}
)
}
private var gradientColor: LinearGradient {
if imageName.hasPrefix("film1") {
return LinearGradient(gradient: Gradient(colors: [.blue, .indigo]), startPoint: .topLeading, endPoint: .bottomTrailing)
} else if imageName.hasPrefix("film2") {
return LinearGradient(gradient: Gradient(colors: [.yellow, .orange]), startPoint: .topLeading, endPoint: .bottomTrailing)
} else {
return LinearGradient(gradient: Gradient(colors: [.purple, .pink]), startPoint: .topLeading, endPoint: .bottomTrailing)
}
}
}
//
struct FilmAnimation_Previews: PreviewProvider {
static var previews: some View {
FilmAnimation()
}
}

View File

@ -0,0 +1,558 @@
import SwiftUI
import SwiftData
import AVKit
// MARK: - Notification Names
extension Notification.Name {
static let blindBoxStatusChanged = Notification.Name("blindBoxStatusChanged")
}
struct BlindBoxView: View {
let mediaType: BlindBoxMediaType
@State private var showModal = false //
@State private var showSettings = false //
@State private var isMember = false //
@State private var memberDate = "" //
@State private var showLogin = false
@State private var memberProfile: MemberProfile? = nil
@State private var blindCount: BlindCount? = nil
@State private var blindList: [BlindList] = [] // Changed to array
//
@State private var blindGenerate : BlindBoxData?
@State private var showLottieAnimation = true
//
@State private var isPolling = false
@State private var pollingTimer: Timer?
@State private var currentBoxType: String = ""
//
@State private var videoURL: String = ""
@State private var imageURL: String = ""
//
@State private var countdown: (minutes: Int, seconds: Int, milliseconds: Int) = (36, 50, 20)
@State private var countdownTimer: Timer?
//
@State private var displayData: BlindBoxData? = nil
@State private var showScalingOverlay = false
@State private var animationPhase: BlindBoxAnimationPhase = .loading
@State private var scale: CGFloat = 0.1
@State private var videoPlayer: AVPlayer?
@State private var showControls = false
@State private var isAnimating = true
@State private var aspectRatio: CGFloat = 1.0
@State private var isPortrait: Bool = false
@State private var displayImage: UIImage?
@State private var showMedia = false
// -
@Query private var login: [Login]
init(mediaType: BlindBoxMediaType) {
self.mediaType = mediaType
}
//
private func startCountdown() {
// 36:50:20
countdown = (36, 50, 20)
countdownTimer?.invalidate()
countdownTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { _ in
var (minutes, seconds, milliseconds) = countdown
//
milliseconds -= 10
if milliseconds < 0 {
milliseconds = 90
seconds -= 1
}
//
if seconds < 0 {
seconds = 59
minutes -= 1
}
//
if minutes <= 0 && seconds <= 0 && milliseconds <= 0 {
countdownTimer?.invalidate()
countdownTimer = nil
return
}
countdown = (minutes, seconds, milliseconds)
}
}
private func loadMedia() {
print("loadMedia called with mediaType: \(mediaType)")
switch mediaType {
case .video:
loadVideo()
currentBoxType = "Video"
startPolling()
case .image:
loadImage()
currentBoxType = "Image"
startPolling()
case .all:
print("Loading all content...")
//
NetworkService.shared.get(
path: "/membership/personal-center-info",
parameters: nil
) { (result: Result<MemberProfileResponse, NetworkError>) in
DispatchQueue.main.async {
switch result {
case .success(let response):
self.memberProfile = response.data
self.isMember = response.data.membershipLevel == "Pioneer"
self.memberDate = response.data.membershipEndAt ?? ""
print("✅ 成功获取会员信息:", response.data)
print("✅ 用户ID:", response.data.userInfo.userId)
case .failure(let error):
print("❌ 获取会员信息失败:", error)
}
}
}
//
NetworkService.shared.get(
path: "/blind_box/available/quantity",
parameters: nil
) { (result: Result<APIResponse<BlindCount>, NetworkError>) in
DispatchQueue.main.async {
switch result {
case .success(let response):
self.blindCount = response.data
print("✅ 成功获取盲盒数量:", response.data)
case .failure(let error):
print("❌ 获取数量失败:", error)
}
}
}
//
NetworkService.shared.get(
path: "/blind_boxs/query",
parameters: nil
) { (result: Result<APIResponse<[BlindList]>, NetworkError>) in
DispatchQueue.main.async {
switch result {
case .success(let response):
self.blindList = response.data ?? []
// none
if self.blindList.isEmpty {
self.animationPhase = .none
}
print("✅ 成功获取 \(self.blindList.count) 个盲盒")
case .failure(let error):
self.blindList = []
self.animationPhase = .none
print("❌ 获取盲盒列表失败:", error.localizedDescription)
}
}
}
}
}
//
private func startPolling() {
stopPolling()
isPolling = true
checkBlindBoxStatus()
}
private func stopPolling() {
pollingTimer?.invalidate()
pollingTimer = nil
isPolling = false
}
private func checkBlindBoxStatus() {
guard !currentBoxType.isEmpty else {
stopPolling()
return
}
NetworkService.shared.postWithToken(
path: "/blind_box/generate/mock",
parameters: ["box_type": currentBoxType]
) { (result: Result<APIResponse<BlindBoxData>, NetworkError>) in
DispatchQueue.main.async {
switch result {
case .success(let response):
let data = response.data
self.blindGenerate = data
print("当前盲盒状态: \(data.status)")
//
if self.mediaType == .all, let firstItem = self.blindList.first {
self.displayData = BlindBoxData(from: firstItem)
} else {
self.displayData = data
}
//
NotificationCenter.default.post(
name: .blindBoxStatusChanged,
object: nil,
userInfo: ["status": data.status]
)
if data.status != "Preparing" {
self.stopPolling()
print("✅ 盲盒准备就绪,状态: \(data.status)")
if self.mediaType == .video {
self.videoURL = data.url ?? ""
} else if self.mediaType == .image {
self.imageURL = data.url ?? ""
}
} else {
self.pollingTimer = Timer.scheduledTimer(
withTimeInterval: 2.0,
repeats: false
) { _ in
self.checkBlindBoxStatus()
}
}
case .failure(let error):
print("❌ 获取盲盒状态失败: \(error.localizedDescription)")
self.stopPolling()
}
}
}
}
private func loadImage() {
guard !imageURL.isEmpty, let url = URL(string: imageURL) else {
print("⚠️ 图片URL无效或为空")
return
}
URLSession.shared.dataTask(with: url) { data, _, _ in
if let data = data, let image = UIImage(data: data) {
DispatchQueue.main.async {
self.displayImage = image
self.aspectRatio = image.size.width / image.size.height
self.isPortrait = image.size.height > image.size.width
self.showScalingOverlay = true //
}
}
}.resume()
}
private func loadVideo() {
guard !videoURL.isEmpty, let url = URL(string: videoURL) else {
print("⚠️ 视频URL无效或为空")
return
}
let asset = AVAsset(url: url)
let playerItem = AVPlayerItem(asset: asset)
let player = AVPlayer(playerItem: playerItem)
let videoTracks = asset.tracks(withMediaType: .video)
if let videoTrack = videoTracks.first {
let size = videoTrack.naturalSize.applying(videoTrack.preferredTransform)
let width = abs(size.width)
let height = abs(size.height)
aspectRatio = width / height
isPortrait = height > width
}
//
videoPlayer = player
videoPlayer?.play()
showScalingOverlay = true //
}
private func prepareVideo() {
guard !videoURL.isEmpty, let url = URL(string: videoURL) else {
print("⚠️ 视频URL无效或为空")
return
}
let asset = AVAsset(url: url)
let playerItem = AVPlayerItem(asset: asset)
let player = AVPlayer(playerItem: playerItem)
let videoTracks = asset.tracks(withMediaType: .video)
if let videoTrack = videoTracks.first {
let size = videoTrack.naturalSize.applying(videoTrack.preferredTransform)
let width = abs(size.width)
let height = abs(size.height)
aspectRatio = width / height
isPortrait = height > width
}
//
videoPlayer = player
}
private func prepareImage() {
guard !imageURL.isEmpty, let url = URL(string: imageURL) else {
print("⚠️ 图片URL无效或为空")
return
}
URLSession.shared.dataTask(with: url) { data, _, _ in
if let data = data, let image = UIImage(data: data) {
DispatchQueue.main.async {
self.displayImage = image
self.aspectRatio = image.size.width / image.size.height
self.isPortrait = image.size.height > image.size.width
}
}
}.resume()
}
private func startScalingAnimation() {
self.scale = 0.1
self.showScalingOverlay = true
withAnimation(.spring(response: 2.0, dampingFraction: 0.5, blendDuration: 0.8)) {
self.scale = 1.0
}
}
// MARK: - Computed Properties
private var scaledWidth: CGFloat {
if isPortrait {
return UIScreen.main.bounds.height * scale * 1/aspectRatio
} else {
return UIScreen.main.bounds.width * scale
}
}
private var scaledHeight: CGFloat {
if isPortrait {
return UIScreen.main.bounds.height * scale
} else {
return UIScreen.main.bounds.width * scale * 1/aspectRatio
}
}
var body: some View {
ZStack {
Color.themeTextWhiteSecondary.ignoresSafeArea()
.onAppear {
print("🎯 BlindBoxView appeared with mediaType: \(mediaType)")
print("🎯 Current thread: \(Thread.current)")
//
if mediaType == .all, let firstItem = blindList.first {
displayData = BlindBoxData(from: firstItem)
} else {
displayData = blindGenerate
}
//
NotificationCenter.default.addObserver(
forName: .blindBoxStatusChanged,
object: nil,
queue: .main
) { notification in
if let status = notification.userInfo?["status"] as? String {
switch status {
case "Preparing":
withAnimation {
self.animationPhase = .loading
}
case "Unopened":
withAnimation {
self.animationPhase = .ready
}
default:
//
withAnimation {
self.animationPhase = .ready
}
break
}
}
}
//
loadMedia()
}
.onDisappear {
stopPolling()
countdownTimer?.invalidate()
countdownTimer = nil
// Clean up video player
videoPlayer?.pause()
videoPlayer?.replaceCurrentItem(with: nil)
videoPlayer = nil
NotificationCenter.default.removeObserver(
self,
name: .blindBoxStatusChanged,
object: nil
)
}
if showScalingOverlay {
MediaOverlayView(
videoPlayer: $videoPlayer,
showControls: $showControls,
mediaType: mediaType,
displayImage: displayImage,
scaledWidth: scaledWidth,
scaledHeight: scaledHeight,
scale: scale,
videoURL: videoURL,
imageURL: imageURL,
blindGenerate: blindGenerate,
onBackTap: {
// BlindOutcomeView
if mediaType == .video, !videoURL.isEmpty, let url = URL(string: videoURL) {
Router.shared.navigate(to: .blindOutcome(media: .video(url, nil), time: blindGenerate?.videoGenerateTime ?? "hhsdshjsjdhn", description:blindGenerate?.description ?? "informationinformationinformationinformationinformationinformation"))
} else if mediaType == .image, let image = displayImage {
Router.shared.navigate(to: .blindOutcome(media: .image(image), time: blindGenerate?.videoGenerateTime ?? "hhsdshjsjdhn", description:blindGenerate?.description ?? "informationinformationinformationinformationinformationinformation"))
}
}
)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.animation(.easeInOut(duration: 1.0), value: scale)
.ignoresSafeArea()
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
withAnimation(.spring(response: 2.5, dampingFraction: 0.6, blendDuration: 1.0)) {
self.scale = 1.0
}
}
}
} else {
// Original content
VStack {
VStack(spacing: 20) {
if mediaType == .all {
BlindBoxNavigationBar(
memberProfile: memberProfile,
showLogin: showLogin,
showUserProfile: showUserProfile
)
}
//
VStack(alignment: .leading, spacing: 4) {
Text("Hi! Click And")
Text("Open Your First Box~")
}
.font(Typography.font(for: .smallLargeTitle))
.fontWeight(.bold)
.foregroundColor(Color.themeTextMessageMain)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal)
.opacity(showScalingOverlay ? 0 : 1)
.offset(y: showScalingOverlay ? -UIScreen.main.bounds.height * 0.2 : 0)
.animation(.easeInOut(duration: 0.5), value: showScalingOverlay)
//
BlindBoxAnimationView(
mediaType: mediaType,
animationPhase: animationPhase,
blindCount: blindCount,
blindGenerate: blindGenerate,
scale: scale,
showScalingOverlay: showScalingOverlay,
showMedia: showMedia,
onBoxTap: {
print("点击了盲盒")
withAnimation {
animationPhase = .opening
}
}
)
//
BlindBoxControls(
mediaType: mediaType,
animationPhase: animationPhase,
countdown: countdown,
onButtonTap: {
if animationPhase == .ready {
//
//
Router.shared.navigate(to: .subscribe)
} else {
showUserProfile()
}
},
onCountdownStart: startCountdown
)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.themeTextWhiteSecondary)
.offset(x: showModal ? UIScreen.main.bounds.width * 0.8 : 0)
.animation(.spring(response: 0.6, dampingFraction: 0.8), value: showModal)
.edgesIgnoringSafeArea(.all)
}
//
SlideInModal(
isPresented: $showModal,
onDismiss: hideUserProfile
) {
UserProfileModal(
showModal: $showModal,
showSettings: $showSettings,
isMember: $isMember,
memberDate: $memberDate
)
}
.offset(x: showSettings ? UIScreen.main.bounds.width : 0)
.animation(.spring(response: 0.6, dampingFraction: 0.8), value: showSettings)
//
ZStack {
if showSettings {
Color.black.opacity(0.3)
.edgesIgnoringSafeArea(.all)
.onTapGesture(perform: hideSettings)
.transition(.opacity)
}
if showSettings {
SettingsView(isPresented: $showSettings)
.transition(.move(edge: .leading))
.zIndex(1)
}
}
.animation(.spring(response: 0.6, dampingFraction: 0.8), value: showSettings)
}
}
.navigationBarBackButtonHidden(true)
}
///
private func showUserProfile() {
withAnimation(.spring(response: 0.6, dampingFraction: 0.8)) {
// print(": \(login.count)")
// for (index, item) in login.enumerated() {
// print(" \(index + 1): =\(item.email), =\(item.name)")
// }
print("当前登录记录:")
for (index, item) in login.enumerated() {
print("记录 \(index + 1): 邮箱=\(item.email), 姓名=\(item.name)")
}
showModal.toggle()
}
}
///
private func hideUserProfile() {
withAnimation(.spring(response: 0.6, dampingFraction: 0.8)) {
showModal = false
}
}
///
private func hideSettings() {
withAnimation(.spring(response: 0.6, dampingFraction: 0.8)) {
showSettings = false
}
}
}
// MARK: -
#Preview {
BlindBoxView(mediaType: .video)
}

View File

@ -0,0 +1,229 @@
import SwiftUI
struct JoinModal: View {
@Binding var isPresented: Bool
var body: some View {
ZStack(alignment: .bottom) {
// Semi-transparent background
if isPresented {
Color.black.opacity(0.4)
.edgesIgnoringSafeArea(.all)
.onTapGesture {
withAnimation {
isPresented = false
}
}
}
// Modal content
if isPresented {
VStack(spacing: 0) {
// IP Image peeking from top
HStack {
// Make sure you have an image named "IP" in your assets
SVGImageHtml(svgName: "IP1")
.frame(width: 116, height: 65)
.offset(x: 30)
Spacer()
}
.frame(height: 65)
VStack(spacing: 0) {
// Close button on the right
HStack {
Spacer()
Button(action: {
withAnimation {
Router.shared.navigate(to: .blindBox(mediaType: .all))
}
}) {
Image(systemName: "xmark")
.font(.system(size: 20, weight: .medium))
.foregroundColor(.themeTextMessageMain)
.padding(12)
}
.padding(.trailing, 16)
}
//
VStack(spacing: 8) {
Text("Join us!")
.font(Typography.font(for: .headline1, family: .quicksandBold))
.foregroundColor(.themeTextMessageMain)
Text("Join us to get more exclusive benefits.")
.font(.system(size: 14, weight: .regular))
.foregroundColor(.themeTextMessageMain)
}
.padding(.vertical, 12)
// List content
VStack (alignment: .leading) {
HStack {
SVGImage(svgName: "JoinList")
.frame(width: 32, height: 32)
HStack (alignment: .top){
Text("Unlimited")
.font(.system(size: 16, weight: .bold))
.foregroundColor(.themeTextMessageMain)
Text(" blind box purchases.")
.font(.system(size: 16, weight: .regular))
.foregroundColor(.themeTextMessageMain)
}
}
.padding(.vertical, 12)
.padding(.leading,12)
HStack (alignment: .center) {
SVGImage(svgName: "JoinList")
.frame(width: 32, height: 32)
VStack (alignment: .leading,spacing: 4) {
HStack {
Text("Freely")
.font(.system(size: 16, weight: .bold))
.foregroundColor(.themeTextMessageMain)
Text(" upload image and video")
.font(.system(size: 16, weight: .regular))
.foregroundColor(.themeTextMessageMain)
}
Text(" materials.")
.font(.system(size: 16, weight: .regular))
.foregroundColor(.themeTextMessageMain)
}
}
.padding(.vertical, 12)
.padding(.leading,12)
HStack(alignment: .top) {
SVGImage(svgName: "JoinList")
.frame(width: 32, height: 32)
VStack (alignment: .leading,spacing: 4) {
HStack {
Text("500")
.font(.system(size: 16, weight: .bold))
.foregroundColor(.themeTextMessageMain)
Text(" credits daily,")
.font(.system(size: 16, weight: .regular))
.foregroundColor(.themeTextMessageMain)
}
HStack(alignment: .top) {
VStack (alignment: .leading, spacing: 4) {
HStack {
Text("5000")
.font(.system(size: 16, weight: .bold))
.foregroundColor(.themeTextMessageMain)
Text(" permanent credits on your first")
.font(.system(size: 16, weight: .regular))
.foregroundColor(.themeTextMessageMain)
}
Text(" purchase!")
.font(.system(size: 16, weight: .regular))
.foregroundColor(.themeTextMessageMain)
}
}
}
}
.padding(.top, 12)
.padding(.leading,12)
HStack {
Spacer() // This will push the button to the right
Button(action: {
//
Router.shared.navigate(to: .subscribe)
}) {
HStack {
Text("See More")
.font(.system(size: 16))
Image(systemName: "chevron.right")
.font(.system(size: 14))
}
.foregroundColor(.themeTextMessageMain)
.padding(.vertical, 12)
.padding(.horizontal, 24)
.cornerRadius(20)
}
}
.padding(.trailing, 16) // Add some right padding to match the design
Button(action: {
//
Router.shared.navigate(to: .subscribe)
}) {
HStack {
Text("Subscribe")
.font(Typography.font(for: .body, family: .quicksandBold))
Spacer()
Text("$1.00/Mon")
.font(Typography.font(for: .body, family: .quicksandBold))
}
.foregroundColor(.themeTextMessageMain)
.padding(.vertical, 12)
.padding(.horizontal, 30)
.background(Color.themePrimary)
.cornerRadius(20)
}
.padding(.top, 16)
//
HStack(alignment: .center) {
Button(action: {
// Action for Terms of Service
if let url = URL(string: "https://memorywake.com/privacy-policy") {
UIApplication.shared.open(url)
}
}) {
Text("Terms of Service")
.font(.system(size: 12, weight: .regular))
.foregroundColor(.themeTextMessage)
.underline() // Add underline
}
Rectangle()
.fill(Color.gray.opacity(0.5))
.frame(width: 1, height: 16)
.padding(.vertical, 4)
Button(action: {
//
if let url = URL(string: "https://memorywake.com/privacy-policy") {
UIApplication.shared.open(url)
}
}) {
Text("Privacy Policy")
.font(.system(size: 12, weight: .regular))
.foregroundColor(.themeTextMessage)
.underline() // Add underline
}
Rectangle()
.fill(Color.gray.opacity(0.5))
.frame(width: 1, height: 16)
.padding(.vertical, 4)
Button(action: {
// Action for Restore Purchase
if let url = URL(string: "https://memorywake.com/privacy-policy") {
UIApplication.shared.open(url)
}
}) {
Text("AI Usage Guidelines")
.font(.system(size: 12, weight: .regular))
.foregroundColor(.themeTextMessage)
.underline() // Add underline
}
}
.padding(.bottom, 24)
.frame(maxWidth: .infinity, alignment: .center)
}
.padding(.horizontal, 16)
}
.background(Color.white)
.cornerRadius(20, corners: [.topLeft, .topRight])
}
.frame(height: nil)
.transition(.move(edge: .bottom))
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom)
.edgesIgnoringSafeArea(.all)
.animation(.easeInOut, value: isPresented)
}
}
struct JoinModal_Previews: PreviewProvider {
static var previews: some View {
JoinModal(isPresented: .constant(true))
}
}