반응형

 

Hacking with Swift 사이트의 강좌 번역본입니다.

 

[원문 : https://www.hackingwithswift.com/quick-start/swiftui/how-to-draw-a-checkerboard]

 

How to draw a checkerboard

 

SwiftUI의 path는 연속적일 필요가 없고, 분리된 도형은 대신 여러개의 사각형, 타원, 등등, 모두 하나로 결합될 수 있습니다.

 

이를 증명하는 쉬운 방법은, 다음과 같이 일련의 사각형을 만들어 행과 열을 설정함으로써 체스판 도형을 작성할 수 있습니다.

struct Checkerboard: Shape {
    let rows: Int
    let columns: Int

    func path(in rect: CGRect) -> Path {
        var path = Path()

        // figure out how big each row/column needs to be
        let rowSize = rect.height / CGFloat(rows)
        let columnSize = rect.width / CGFloat(columns)

        // loop over all rows and columns, making alternating squares colored    
        for row in 0 ..< rows {
            for column in 0 ..< columns {
                if (row + column).isMultiple(of: 2) {
                    // this square should be colored; add a rectangle here
                    let startX = columnSize * CGFloat(column)
                    let startY = rowSize * CGFloat(row)

                    let rect = CGRect(x: startX, y: startY, width: columnSize, height: rowSize)
                    path.addRect(rect)
                }
            }
        }

        return path
    }
}

 

이제 행과 열을 전달하고 합리적인 영역(frame)을 제공함으로써 해당 도형을 사용할 수 있습니다.

struct ContentView: View {
    var body: some View {
        Checkerboard(rows: 16, columns: 16)
            .fill(Color.red)
            .frame(width: 200, height: 200)    
    }
}

 

반응형

'SwiftUI > Drawing' 카테고리의 다른 글

How to create a spring animation  (0) 2019.11.28
How to use UIBezierPath and CGPath in SwiftUI  (0) 2019.11.28
How to draw polygons and stars  (0) 2019.11.28
How to draw a custom path  (0) 2019.11.28
SwiftUI’s built-in shapes  (0) 2019.11.28
Posted by 까칠코더
,