ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Core Graphics
    iOS 2021. 3. 29. 16:41

    안녕하세요. 그린입니다🟢

    오늘 포스팅은 Core Graphics(코어 그래픽스)에 대해 알아보겠습니다🤓

    Core Graphics란?

     : Quarts(쿼츠)라는 그래픽 라이브러리 안에 들어있는 기술을 활용하여

       2D 렌더링, 수행 경로 기반 드로잉, 안티 얼리어싱 렌더링, 그라디언트, 이미지, 색상, PDF 문서 등등의 처리를 해주는 라이브러리!!

     : 코어 그래픽스 프레임 워크는 쿼츠 드로잉 엔진 기반으로한 2D 작업 (CG가 앞에 붙은것들..!)

       -> 2차원 그래픽을 그릴 수 있는 그래픽 라이브러리

    Quarts?

     : 코어 그래픽스 + 코어 애니메이션으로 구성 (하나의 라이브러리가 아님)

    drawRect

     : 그리기를 해줌

    점/좌표/픽셀

     : CGFloat 형태로 왼쪽 상단 0,0 부터 위치를 나타내줌

    CGSize

     : 두개의 CGFloat 값으로 넓이 / 높이 나타내줌

    Graphic Context

     : 쿼츠 API 함수 호출로 인자 넘겨받은 그래픽 콘텍스트 필요 (그리기 정보)

     : UIGraphicsGetCurrentContext() 함수 호출로 그래픽 콘텍스트 정보를 얻어 그릴 준비를 함

    코어 그래픽스를 활용하여 그려보기!

     : 원 안에 체크표시를 찍어보기

    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)
        }
    }

     1)  @IBDesignable: 해당 그리려는 요소 클래스에 선언해주면 빌드를 거쳐 뮬레이터로 확인하지 않아도 실시간으로 스토리보드에서

         해당 그리기가 구현된것이 보여지도록 해줌
     -> 스토리보드 상 buildFail 발생 시
        : 프로젝트 빌드세팅 -> Build Active Architecture only (No) -> Editor -> Refresh All Views

     2) 스토리보드에 그린 정보 담아줄 요소 추가 -> class를 그리기 구현해준것으로 채택해줌

     3) draw 메서드 override하여 그리기

     4) context 선언

     5) context에 그릴 정보 담아주기

      -. insetBy() -> bounds.insetBy(dx: bounds.width * 0.1, dy: bounds.height * 0.1): 들여서 간격 벌려 그리기 위한 속성
      -. context.beginPath(): 그리기 시작할것이라는 선언
      -. context.setLineWidth(): 두께
      -. context.setStrokeColor(): 외부선 색상
      -. context.setFillColor(): 내부 색상
      -. context.addEllipse(): 안에 채울것 (그린게 아님 -> 그릴것이다 예정한것) // 동그라미 형태로 그려줌!!
      -. context.addRect(): 해당 버튼 뷰에 맞게 그려줌 (별도 설정 없을 시 네모낳게 나옴)
      -. context.drawPath(using: .fillStroke): 그리기✍️
      -. context.closePath(): 그리기 마치기

    6) 추가로 그리기

      -> 추가로 그릴것은 또 begin Path해서 콘텍스트 담아줘도됨

      -. setLineJoin/Cap(): 시작/끝처리 (네모,원 등등의 형태)
      -. move() : 해당 위치로 이동
      -. context.addLine(): 이동해서 해당 위치까지 그리기

      -. .stroke: 선으로 그리기

    7) @IBInspectable
     : 요소의 inspector 변경 바로 실시간 확인 가능하도록 선언해줄 수 있음

    Transform

     : 뒤집기/돌리기 등등의 형태 변형에 대해 구현해줄 수 있음

    let transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 2.0))
    self.transform = transform

     -. 회전의 경우 radian값으로 줌

     -. 뷰를 그려줄때 넣어주면 처음부터 변환되어 나타남

    회전 애니메이션

     : 클릭 되었을때 애니메이션 효과 부여할 수 있음

    import UIKit
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
        }
        
        @IBAction func rotate(_ sender: UIButton) {
            let transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 2.0))
            
            UIView.animate(withDuration: 0.3) {
                sender.frame.origin.y += 10
                sender.transform = transform
            }
        }
    }

     

     

    [느낀점]

    코어 그래픽스로 아주아주 다양한 효과를 줄 수 있을것 같다. 다만 다 일일히 구현해주고 라디안값과 위치와 그 모든것을 생각해내면서

    하드코딩을 해줘야하는것이 여간 머리 아픈일이 아닐 수 없다...😱
    그렇지만 개발 환경이 어떻게 돌아갈지 협업이 어떻게 진행될지 모르기에 꼭 알고 있어야되는 핵심 개념이라고 느껴졌다..!

    지금은 간단한 2D 랜더링이지만 좀 더 복잡하고 세련된 구현을 하는 그날까지...!👊🏻

     

    [참고자료]

    야곰 iOS-startcamp 코어 그래픽스 관련 활동학습

    https://developer.apple.com/documentation/coregraphics

    https://developer.apple.com/documentation/uikit/views_and_controls/uikit_catalog_creating_and_customizing_views_and_controls

    https://moonibot.tistory.com/49

    https://ruwen.tistory.com/5

    https://bite-sized-learning.tistory.com/503
    https://zeddios.tistory.com/270

    'iOS' 카테고리의 다른 글

    Core Animation  (0) 2021.04.01
    Homebrew & Vapor Toolbox  (0) 2021.03.30
    Localization  (0) 2021.03.25
    User Notification (2)  (0) 2021.03.23
    OAuth  (0) 2021.03.22
Designed by Tistory.