[swift] 그래픽 프리미티브 함수

Swift는 그래픽 프로그래밍을 할 때 기본적인 그래픽 요소를 생성하는 데 사용되는 몇 가지 편리한 함수들을 제공합니다. 이러한 함수들은 간단한 원, 선, 사각형 등의 기본적인 도형들을 생성하고 조작하는 데 도움을 줍니다. 이번 블로그에서는 Swift에서 기본적인 그래픽 프리미티브 함수들을 소개하고 간단한 예제를 통해 이해해 보겠습니다.

목차

  1. 원 그리기
  2. 선 그리기
  3. 사각형 그리기

원 그리기

원을 그리기 위해서는 UIBezierPath 클래스의 메서드를 사용합니다. 아래는 원을 생성하고 화면에 표시하는 간단한 예제입니다.

import UIKit

func drawCircle() {
    let circlePath = UIBezierPath(arcCenter: CGPoint(x: 100, y: 100), radius: 50, startAngle: 0, endAngle: .pi * 2, clockwise: true)

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = circlePath.cgPath

    shapeLayer.fillColor = UIColor.red.cgColor
    shapeLayer.strokeColor = UIColor.blue.cgColor
    shapeLayer.lineWidth = 3

    view.layer.addSublayer(shapeLayer)
}

UIBezierPath를 사용하여 원의 경로를 만들고, CAShapeLayer를 사용하여 경로를 그래픽으로 표시합니다.

선 그리기

평평한 선을 그리기 위해서는 UIBezierPath를 사용합니다. 아래는 화면에 수평한 선을 그리는 예제입니다.

import UIKit

func drawLine() {
    let linePath = UIBezierPath()
    linePath.move(to: CGPoint(x: 50, y: 50))
    linePath.addLine(to: CGPoint(x: 200, y: 50))

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = linePath.cgPath

    shapeLayer.strokeColor = UIColor.green.cgColor
    shapeLayer.lineWidth = 2

    view.layer.addSublayer(shapeLayer)
}

위의 코드에서 UIBezierPath로 선의 시작점과 끝점을 지정하고, CAShapeLayer를 사용하여 선을 그래픽으로 표시합니다.

사각형 그리기

UIBezierPath 클래스를 사용하여 사각형을 그릴 수도 있습니다. 아래는 화면에 사각형을 그리는 예제입니다.

import UIKit

func drawRectangle() {
    let rectanglePath = UIBezierPath(rect: CGRect(x: 50, y: 100, width: 200, height: 100))

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = rectanglePath.cgPath

    shapeLayer.fillColor = UIColor.yellow.cgColor
    shapeLayer.strokeColor = UIColor.purple.cgColor
    shapeLayer.lineWidth = 2

    view.layer.addSublayer(shapeLayer)
}

UIBezierPath를 사용하여 사각형의 경로를 만들고, CAShapeLayer를 사용하여 경로를 그래픽으로 표시합니다.

이러한 기본적인 그래픽 프리미티브 함수들을 사용하여 원, 선, 사각형 등을 생성하고 조작할 수 있습니다. 앱의 사용자 인터페이스에 다양한 그래픽 요소를 추가할 때 유용하게 활용할 수 있습니다.

참조:

이상으로 Swift에서 그래픽 프리미티브 함수에 대해 알아보았습니다. 감사합니다!