SwiftUI – draw Path

Draw Path

This sample is inspired by Apple Documentation

Draw something using Path and use this View in other Parent View

View

This is an example to draw path in View.

SemanDomanView.swift

import SwiftUI

struct SemanDomanView: View {
    var body: some View {
        GeometryReader { geometry in
            Path { path in
                let width = min(geometry.size.width, geometry.size.height)
                
                path.move(to: CGPoint(x: width / 2 - 150, y:125))
                path.addLine(to: CGPoint(x: width / 2 + 150, y:125))
                path.addLine(to: CGPoint(x: width / 2 - 95, y:300))
                path.addLine(to: CGPoint(x: width / 2, y: 10))
                path.addLine(to: CGPoint(x: width / 2 + 95, y:300))
                path.addLine(to: CGPoint(x: width / 2 - 150, y:125))
                
            }.stroke(Color.red, lineWidth: 5)
        }
    }
}

struct SemanDomanView_Previews: PreviewProvider {
    static var previews: some View {
        SemanDomanView()
    }
}

GeometryReader to measure parent View size.

SymbolsView.swift

Let’s use SemanDoman in other View

Draw multiple in View and rotate in certain area.

import SwiftUI

struct SymbolsView: View {
    
    let angle: Angle
    
    var body: some View {
        ZStack {
            SemanDomanView()
            SemanDomanView()
            .rotationEffect(angle, anchor: .bottom)
            SemanDomanView()
                .rotationEffect(.init(degrees: 30), anchor: .bottom)
        }.frame(width: 400, height: 400, alignment: .center)
    }
}

struct SymbolsView_Previews: PreviewProvider {
    static var previews: some View {
        SymbolsView(angle: .init(degrees: 15))
    }
}

iOS
スポンサーリンク
Professional Programmer2

コメント