[swift] Swift Core Graphics로 원형 프로그레스 바 만들기

iOS 앱을 개발할 때, 우리는 종종 사용자에게 어떤 작업이 진행 중인지 시각적으로 알려주고 싶을 때가 있습니다. 이때 프로그레스 바가 유용하게 사용됩니다. 이번 글에서는 Swift 언어를 사용하여 Core Graphics를 이용해 원형 프로그레스 바를 만드는 방법에 대해 알아보겠습니다.

1. 프로젝트 설정

우선 새로운 Xcode 프로젝트를 만들고, Storyboard를 사용하지 않고 코드로 뷰를 생성하는 방식을 선택합니다. 이후 해당 뷰에 Core Graphics를 이용하여 원형 프로그레스 바를 그리겠습니다.

2. Core Graphics를 이용한 View 생성

먼저, 원형 프로그레스 바를 그릴 커스텀 뷰를 생성합니다.

import UIKit

class CircularProgressBarView: UIView {

    private var progressLayer = CAShapeLayer()

    override init(frame: CGRect) {
        super.init(frame: frame)
        createCircularPath()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        createCircularPath()
    }

    private func createCircularPath() {
        let circularPath = UIBezierPath(
            arcCenter: CGPoint(x: frame.size.width / 2, y: frame.size.height / 2),
            radius: frame.size.width / 2 - 10, 
            startAngle: -CGFloat.pi / 2, 
            endAngle: 2 * CGFloat.pi, 
            clockwise: true
        )
        
        progressLayer.path = circularPath.cgPath
        progressLayer.strokeColor = UIColor.blue.cgColor
        progressLayer.lineWidth = 10.0
        progressLayer.fillColor = UIColor.clear.cgColor
        progressLayer.lineCap = .round
        layer.addSublayer(progressLayer)
    }
}

위의 코드에서 우리는 CircularProgressBarView를 생성하고, createCircularPath 메서드를 통해 원형 프로그레스 바를 그리는 작업을 실시합니다.

3. 프로그레스 표현

이제 이 뷰를 통해 프로그레스를 표현하기 위해 필요한 메서드들을 추가할 차례입니다.

extension CircularProgressBarView {
    func setProgress(to progressConstant: CGFloat, withAnimation: Bool) {
        let animation = CABasicAnimation(keyPath: "strokeEnd")
        animation.toValue = progressConstant / 100
        animation.duration = 2
        animation.fillMode = CAMediaTimingFillMode.forwards
        animation.isRemovedOnCompletion = false
        progressLayer.add(animation, forKey: "ani")
    }
}

위의 코드는 setProgress 메서드를 추가하여 프로그레스 바에 애니메이션을 적용하는 과정을 나타냅니다.

이제 원형 프로그레스 바를 생성하고, 프로그레스를 표현하기 위한 메서드들을 정의했습니다. 해당 뷰를 사용하여 프로젝트에 적용하고, 여러 가지 추가적인 기능들을 조합해 보실 수 있을 것입니다.

결론

Swift 언어의 Core Graphics를 이용하여 원형 프로그레스 바를 만드는 방법에 대해 알아보았습니다. 이를 통해 사용자에게 진행 중인 작업을 시각적으로 표현하는 방법을 배우셨을 것입니다. 이를 활용하여 보다 다채로운 사용자 경험(UX)을 제공해 보시기 바랍니다.

참고 문헌:

다른 질문이 있으시면 언제든지 물어보세요!