LoginSignup
4
3

【SwiftUI】削って遊べるスクラッチを作ってみる

Posted at

はじめに

削って何の絵が出てくるでしょう?みたいなスクラッチゲームを作ってみます。

サンプルアプリ

Simulator Screen Recording - iPhone 15 Pro - 2024-02-29 at 21.09.57.gif

実装

import SwiftUI

struct DrawLine: Identifiable {
    let id = UUID()
    var points: [CGPoint]
}

struct ContentView: View {
    
    @State private var pastLines: [DrawLine] = []
    
    @State private var currentLine: DrawLine?
    
    var body: some View {
        VStack {
            Text("スクラッチ")
                .font(.title)
            Text("削れ")
                .font(.title2)
            
            Image(.icon)
                .resizable()
                .scaledToFit()
                .gesture(dragGesture)
                .mask(maskView)
                .border(.black)
            
            Button {
                pastLines = []
            } label: {
                Text("リセット")
            }
        }
    }
    
    private var dragGesture: some Gesture {
        DragGesture(minimumDistance: 0, coordinateSpace: .local)
            .onChanged({ value in
                if currentLine == nil {
                    currentLine = DrawLine(points: [])
                }
                guard var line = currentLine else { return }
                line.points.append(value.location)
                currentLine = line
            })
            .onEnded({ value in
                guard var line = currentLine else { return }
                line.points.append(value.location)
                pastLines.append(line)
                currentLine = nil
            })
    }
    
    private var maskView: some View {
        ZStack {
            ForEach(pastLines) { line in
                Path { path in
                    path.addLines(line.points)
                }
                .stroke(Color.red, lineWidth: 20)
            }
            .clipped()
            
            Path { path in
                guard let line = currentLine else { return }
                path.addLines(line.points)
            }
            .stroke(Color.red, lineWidth: 20)
            .clipped()
        }
    }
}

おわり

これを応用すれば、なぞった部分だけモザイクをかけるといったアプリを作ることができますね

参考記事

4
3
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
4
3