3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Qiita全国学生対抗戦Advent Calendar 2023

Day 6

【SwiftUI】TimelineViewを使って波を作る

Posted at

はじめに

TimelineViewを使って波を作ってみました。
繰り返しのアニメーションはTimelineViewと相性が良さそうです。

サンプルアプリ

Simulator Screen Recording - iPhone 15 - 2023-12-06 at 22.14.44.gif

実装

import SwiftUI

struct ContentView: View {
    var body: some View {
        TimelineView(.animation) { timeline in
            GeometryReader { geometry in
                Path { path in
                    path.move(to: CGPoint(x: 0, y: geometry.size.height / 2))
                    
                    // stride(from: 開始値, to: 終了値, by: 刻み幅)
                    /// `by`の刻み幅を`to`に追加しないと右側に隙間が発生しちゃう
                    stride(from: 0, to: geometry.size.width + 3, by: 3).forEach { x in
                        let time = timeline.date.timeIntervalSince1970
                        let y = sin(Double(x) / 180.0 * .pi + time) * 20 + Double(geometry.size.height / 2)
                        path.addLine(to: CGPoint(x: x, y: CGFloat(y)))
                    }
                    
                    // 波の下半分を塗りつぶす
                    path.addLine(to: CGPoint(x: geometry.size.width, y: geometry.size.height))
                    path.addLine(to: CGPoint(x: 0, y: geometry.size.height))
                    path.closeSubpath()
                }
                .fill(.blue)
            }
        }
        .ignoresSafeArea()
    }
}

おわり

いい感じにできました。

参考記事

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?