iOS/코드조각

[iOS, Swift] UIBezierPath 예제

검은참깨두유vm 2022. 8. 25. 12:54
반응형

iOS 15.5, Xcode 13.31, Swift 5, UIKit 환경에서 진행했습니다.

 

import UIKit

class MyCustomView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setup()
    }
    
    func setup() {
        let shapedLayer = CAShapeLayer()
        
        shapedLayer.path = createBezierPath().cgPath
        shapedLayer.strokeColor = UIColor.blue.cgColor
        shapedLayer.fillColor = UIColor.white.cgColor
        shapedLayer.lineWidth = 1.0
        shapedLayer.position = CGPoint(x: 10, y: 10)
        
        self.layer.addSublayer(shapedLayer)
    }
    
    func createBezierPath() -> UIBezierPath {
        // create a new path
        let path = UIBezierPath()
        
        // starting point for the path (bottom left)
        path.move(to: CGPoint(x: 2, y: 26))
        
        // left line
        path.addLine(to: CGPoint(x: 2, y: 15))
        
        // left curve
        path.addCurve(to: CGPoint(x: 0, y: 12), // ending point
                      controlPoint1: CGPoint(x: 2, y: 14),
                      controlPoint2: CGPoint(x: 0, y: 14))
        
        // left line
        path.addLine(to: CGPoint(x: 0, y: 2))
        
        // Top side
        // arc
        path.addArc(withCenter: CGPoint(x: 2, y: 2), radius: 2, startAngle: CGFloat(Double.pi), endAngle: CGFloat(3*Double.pi/2), clockwise: true)
        path.addLine(to: CGPoint(x: 8, y: 0))
        path.addArc(withCenter: CGPoint(x: 8, y: 2), radius: 2, startAngle: CGFloat(3*Double.pi/2), endAngle: CGFloat(0), clockwise: true)
        path.addLine(to: CGPoint(x: 10, y: 12))
        path.addCurve(to: CGPoint(x: 8, y: 15),
                      controlPoint1: CGPoint(x: 10, y: 14),
                      controlPoint2: CGPoint(x: 8, y: 14))
        path.addLine(to: CGPoint(x: 8, y: 26))
        
        // Bottom side
        path.close()
        
        return path
    }
    
}

UIBazierPath를 생성한 후, addLine, addArc, addCurve등의 메소드를 통하여 path를 그려준 후,

CAShapedLayer().path에 UIBazierPath를 등록하여준다.

 

 

반응형