본문 바로가기

IT/swift

iOS 코어그래픽스 이용 그래픽 그리기

반응형

프로젝트를 하나 신규 한다.

 

왼쪽 프로젝트 네비게이터에서 컨트롤 클릭 > New File

 

Cocoa Touch Class 선택

 

Draw2D 라고 Class 이름을 지정하고, Subclass of : UIView 를 선택

 

Main 을 눌러 메인스토리보드를 선택하고, ViewController 밑의 View 를 방금 생성한 Draw2D 로 선택한다. 

 == 오른쪽 패널의 Identity Inspector( 명함같이 생김 ) Class 에 방금 생성한 Draw2D를 선택하는것

 

Draw2D.swift 파일에 아래 같이 입력한다.

 

//
//  Draw2D.swift
//  Draw2D
//
//  Created by HanTaeJong on 2022/09/03.
//

import UIKit

class Draw2D: UIView {

    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()!
        context.setLineWidth(2.0)
        context.setStrokeColor(UIColor.blue.cgColor)

         //create a path

        context.beginPath()
        context.move(to: CGPoint(x:100,y:100))
        context.addLine(to: CGPoint(x:150, y:150))
        context.addLine(to: CGPoint(x:100, y:200))
        context.addLine(to: CGPoint(x:50, y:150))
        context.addLine(to: CGPoint(x:100, y:100))
        context.strokePath()
    }
}

사각형 그리기

        context.beginPath()
        context.addRect(CGRect(x: 100, y: 100, width: 100, height: 100))
        context.strokePath()

 

타원 및 원형 그리기

        context.beginPath()
        context.addEllipse(in: CGRect(x: 100, y: 100, width: 200, height: 100))
        context.strokePath()

색 채워서 그리기--> fillPath 함수를 사용한다.

        context.beginPath()
        context.addEllipse(in: CGRect(x: 100, y: 100, width: 200, height: 100))
        context.setFillColor(UIColor.red.cgColor)
        context.fillPath()

호 그리기

        context.beginPath()
        context.move(to: CGPoint(x: 100, y: 100))
        context.addArc(tangent1End: CGPoint(x: 100, y: 200), tangent2End: CGPoint(x: 300, y: 200), radius: 100)
        context.strokePath()

그림자 넣기 setShadow

        context.beginPath()
        context.move(to: CGPoint(x: 100, y: 100))
        context.addArc(tangent1End: CGPoint(x: 100, y: 200), tangent2End: CGPoint(x: 300, y: 200), radius: 100)
        context.setShadow(offset: CGSize(width: -10, height: 15), blur: CGFloat())
        context.strokePath()
반응형