draw(_:)(drawRect) 함수를 override해서 그림
override func drawRect(regionThatNeedsToBeDrawn: CGRect)// draw(_ :)로 변경됨
override func draw(_ rect: CGRect)
draw(_ :) : 뷰에서 CGRect 직사각형으로 특정된 영역에 대해 뷰를 다시 그리는 등 업데이트 할 때 호출되는 메서드
draw(_ :) 메서드는 UIView의 인스턴스 메서드로, UIView 객체 인스턴스로부터 접근해서 사용하는 메서드. 인자로는 CGRect(CoreGraphics Rect)를 받아서 해당 Rect를 다시 그려주는 업데이트 하는 역할로 사용 됨. 해당 rect의 범위는 업데이트 되는 뷰의 bounds 비율
drawRect를 실행하는방법
Core Graphics란 Quarts(쿼츠)라는 그래픽 라이브러리 안에 들어있는 기술을 활용하여 2D 렌더링, 수행 경로 기반 드로잉, 안티 얼리어싱 렌더링, 그라디언트, 이미지, 색상 PDF 문서 등등의 처리를 해주는 라이브러리.
Core Graphics 프레임워크는 쿼츠 드로잉 엔진 기반으로한 2D작업(앞에 CG가 붙은것들) -> 2차원 그래픽을 그릴 수 있는 그래픽 라이브러리
import Foundation
import UIKit
@IBDesignable
class Button: UIButton {
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else {
return
}
let circleRect = bounds.insetBy(dx: bounds.height * 0.1, dy: bounds.width * 0.1)
//원 그리기
context.beginPath()
context.setLineWidth(10)
context.setStrokeColor(UIColor.systemRed.cgColor)
context.setFillColor(UIColor.systemGreen.cgColor)
context.addEllipse(in: circleRect)
context.drawPath(using: .fillStroke)
context.closePath()
//체크 표시 그리기
context.beginPath()
context.setLineWidth(15)
context.setLineJoin(.round)
context.setLineCap(.square)
context.move(to: CGPoint(x: bounds.width * 0.15, y: bounds.height * 0.5))
context.addLine(to: CGPoint(x: bounds.width * 0.4, y: bounds.height * 0.8))
context.addLine(to: CGPoint(x: bounds.width * 0.8, y: bounds.height * 0.3))
context.drawPath(using: .stroke)
}
}
UIBezierPath는 UIKit에서 그리기에 속해있는 클래스. view에서 렌더링 할 수 있는 직선과 곡선으로 구성된 경로
let path = UIBezierPath()
path.lineWidth = 10
path.lineJoinStyle = .round
path.move(to: CGPoint(x: 100, y:100))
path.addLine(to: CGPoing(x: 100, y: 200))
path.close()