반응형

 

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

 

[원문 : https://www.hackingwithswift.com/quick-start/swiftui/how-to-draw-polygons-and-stars]

 

How to draw polygons and stars

 

SwiftUI의 기본 path 그리는 시스템을 이해하면, 모든 종류의 도형을 쉽게 추가할 수 있습니다. 예를들어, 약간의 수학만으로 다향안 별 도형 또는 다른 다각형을 표현할 수 있는, Star 도형을 만들 수 있습니다.

 

예를들어:

struct Star: Shape {
    // store how many corners the star has, and how smooth/pointed it is
    let corners: Int
    let smoothness: CGFloat

    func path(in rect: CGRect) -> Path {
        // ensure we have at least two corners, otherwise send back an empty path
        guard corners >= 2 else { return Path() }

        // draw from the center of our rectangle
        let center = CGPoint(x: rect.width / 2, y: rect.height / 2)

        // start from directly upwards (as opposed to down or to the right)
        var currentAngle = -CGFloat.pi / 2

        // calculate how much we need to move with each star corner
        let angleAdjustment = .pi * 2 / CGFloat(corners * 2)

        // figure out how much we need to move X/Y for the inner points of the star
        let innerX = center.x * smoothness
        let innerY = center.y * smoothness

        // we're ready to start with our path now
        var path = Path()

        // move to our initial position
        path.move(to: CGPoint(x: center.x * cos(currentAngle), y: center.y * sin(currentAngle)))

        // track the lowest point we draw to, so we can center later
        var bottomEdge: CGFloat = 0

        // loop over all our points/inner points
        for corner in 0..<corners * 2  {
            // figure out the location of this point
            let sinAngle = sin(currentAngle)
            let cosAngle = cos(currentAngle)
            let bottom: CGFloat

            // if we're a multiple of 2 we are drawing the outer edge of the star
            if corner.isMultiple(of: 2) {
                // store this Y position
                bottom = center.y * sinAngle

                // …and add a line to there
                path.addLine(to: CGPoint(x: center.x * cosAngle, y: bottom))
            } else {
                // we're not a multiple of 2, which means we're drawing an inner point

                // store this Y position
                bottom = innerY * sinAngle

                // …and add a line to there
                path.addLine(to: CGPoint(x: innerX * cosAngle, y: bottom))
            }

            // if this new bottom point is our lowest, stash it away for later
            if bottom > bottomEdge {
                bottomEdge = bottom
            }

            // move on to the next corner
            currentAngle += angleAdjustment
        }

        // figure out how much unused space we have at the bottom of our drawing rectangle
        let unusedSpace = (rect.height / 2 - bottomEdge) / 2

        // create and apply a transform that moves our path down by that amount, centering the shape vertically
        let transform = CGAffineTransform(translationX: center.x, y: center.y + unusedSpace)
        return path.applying(transform)
    }
}

 

다음과 같이 Star 도형을 사용할 수 있습니다

struct ContentView: View {
    var body: some View {
        Star(corners: 5, smoothness: 0.45)
            .fill(Color.red)
            .frame(width: 200, height: 200)
            .background(Color.green)

    }
}

 

별은 다각형일뿐이며, smoothness를 1 증가하는 경우 코드를 변경하지 않고도 육각형과 팔각형 같은 도형을 그릴 수 있습니다.

반응형

'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 a checkerboard  (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 까칠코더
,