will come true

[Android] 그리기 관련 메서드 - Canvas, Paint, Bitmap, Path, BitmapFactory, RectF 본문

Android

[Android] 그리기 관련 메서드 - Canvas, Paint, Bitmap, Path, BitmapFactory, RectF

haehyun 2022. 4. 23. 22:57

안드로이드에서는 Canvas에 그래픽을 그리고, Bitmap을 이용해서 그래픽을 불러와 화면에 그린다.
또는 Paint에 펜의 스타일을 설정해두고, 이 펜 설정대로 Canvas에 특정한 색상·모양의 도형을 그릴 수 있다.

  1. View를 상속받는 CustomView 클래스를 생성한다.
  2. Canvas에 그리고 싶은 내용을 onDraw() 에 작성한다.
    onDraw()는 View로 부터 상속받은 메서드이며 Canvas 타입 객체를 인자로 받는다. 이 Canvas 객체가 해당 뷰의 기본 캔버스이며, 여기에 canvas.drawXXX() 메서드를 사용해 그래픽(선, 도형, 이미지 등)을 그릴 수 있다.
    onDraw() 안에서 여러 그리기 메서드를 호출하여 Canvas를 새롭게 갱신하는 것이다.

Canvas

  • Canvas는 View의 그리드 표면, 뷰에 그림을 그릴 수 있는 도화지(Canvas)이다.
  • View 클래스의 onDraw() 메서드의 인수로 전달되므로, 이를 받아서 사용하면 된다.
주요 메서드
void drawPoint(float x, float y, Paint paint)
void drawLine(float startX, float startY, float stopX, float stopY, Paint paint)
void drawLines(float[] pts, Paint paint) 선 집합
void drawCircle(float cx, float cy, float radius, Paint paint) 원형
void drawRect(float left, float top, float right, float bottom, Paint paint)
void drawRect(Rect r, Paint paint)
사각형
void drawText(String text, float x, float y, Paint paint) 텍스트
void drawARGB(int a, int r, int g, int b)
void drawRGB(int r, int g, int b)
void drawColor(int color)
색칠
void drawPath(Path path, Paint paint) 이동 경로 (=연속되는 꺾은 선)
void drawPaint(Paint paint) Paint 객체
void drawBitmap(Bitmap bitmap, float left, float top, Paint paint) Bitmap 객체
void invalidate() 캔버스 새로 그리기 (지금까지 그린 것들을 갱신하여 View에 반영)

 

Paint

  • Paint는 그리기에 대한 속성 정보(선의 굵기, 색상, 스타일 등)를 가지는 객체.
  • 모든 그리기 함수에 인수로 전달된다.
  • 코틀린에서는 setXXX()과 같은 setter 메서드 대신 프로퍼티로 객체를 설정한다.
    ex) paint.setColor(Color.Black) 대신 paint.color = Color.Black 과 같이 멤버 값을 설정한다.
주요 메서드
void setColor(int color) 색상
void setStyle(Paint.style style) 스타일
- FILL : 채우기 (Default)
- STROKE : 외곽선
- STROKE_AND_FILL : 채우기 + 외곽선
void setStrokeWidth(float width) 굵기
void setStrokeJoin(Paint.Join join) - MITER : 모서리를 90도로 각진 형태 (Default)
- BEVEL : 모서리가 깍인 형태
- ROUND : 둥근 형태
void setStokeCap(Paint.Cap cap) - ROUND : 둥근 모양으로 끝남
- SQUARE : 사각형 모양으로 끝남
- BUTT : 지정한 좌표에서 선이 끝남
void setAntAlias(boolean aa) 안티에일리어싱(anti-aliasing) 기법 적용 여부
*계단식 깨짐 현상을 제거하고 경계면을 부드럽게 처리

 

Bitmap

  • 안드로이드에서 이미지를 표현하기 위해 사용되는 객체.
  • 메모리에서 만들어지는 모든 이미지는 Bitmap 객체로 관리된다.
  • Bitmap 객체를 통해 이미지를 우리가 원하는 대로 조작할 수도 있다.
  • 예를 들어 drawable 폴더에 임포트된 이미지 리소스를 BitmapFactory.decodeResource() 메서드를 사용해 Bitmap 객체로 받은 뒤, 미리 정의된 Bitmap 객체를 화면에 뿌리는 방식이다.
  • Bitmap을 출력할 때는 Canvas의 drawBitmap() 메서드를 사용한다.
주요 메서드
Bitmap createBitmap(int width, int height, Bitmap.Config config) 코드에서 비트맵 생성

 

BitmapFactory

  • Bitmap 객체를 만들어주는 여러가지 decode 함수를 제공한다.
주요 메서드
Bitmap BitmapFactory.decodeBitmap(res: Resources!, id: Int, opt: BitmapFactory.Options!)

 

Matrix

이미지의 확대, 축소, 이동, 회전 등의 이미지 변환 함수를 제공한다.

 

Path

  • 직선, 곡선, 다각형 등의 도형 궤적 정보를 가지는 그래픽 객체. (=이동 경로)
  • Path의 정의만으로는 화면에 표시되지 않으며, Canvas 클래스의 drawPath() 를 호출할 때 앞서 정의해둔 Path를 전달하면 그 경로대로 Canvas에 그린다.
주요 메서드
reset() Path 초기화
moveTo(float x, float y) (x, y)로 기준점 이동 (=시작 위치 초기화)
lineTo(float x, float y) 기준점에서 (x, y)까지 선 그리기
addCircle(float x, float y, float radius, Path.Direction dir)
addRect(RectF rect, Path.Direction dir)
Path.Direction
- CW(clockwise) : 시계 방향
- CCW(counter-clockwise : 반시계 방향
quadTo(float x1, float y1, float x2, float y2) 기준점 → (x1, y1) → (x2, y2) 까지 곡선 그리기
cubicTo(float x1, float y1, float x2, float y2, float x3, float y3) 기준점 → (x1, y1) → (x2, y2) → (x3, y3) 까지 곡선 그리기
rLineTo(float x, float y)
rCubicTo(float x1, float y1, float x2, float y2, float x3, float y3)
앞에 'r'이 붙은 메서드는 기준점을 (0,0)으로 취급.
절대좌표가 아닌 기준점을 기준으로 한 상대좌표로 경로를 나타냄.
close() 경로 닫기, 마지막 포인트 부터 시작 시점까지 이어줌.

 

주요 메서드
drawPath(Path path, Paint paint) 설정한 Path를 Paint 펜 설정대로 화면에 출력.

 

RectF

  • 사각형을 위한 4개 좌표 정보를 다루는 객체
주요 메서드
RectF FloatF(float left, float top, float, right, float bottom) 4개의 좌표로 이루어진 사각형 정보 생성
float centerX() x좌표 중심점
float centerY() y좌표 중심점
float width() 너비
float height() 높이
boolean contains(float left, float top, float right, float bottom)
boolean contains(RectF r)
boolean contains(float x, float y)
해당 사각형 영역 안에 포함되는지 여부
boolean intersect(RectF r)
boolean intersect(float left, float top, float right, float bottom)
해당 사각형과 교차하는지 여부
boolean isEmpty() 사각형이 비어있는지 여부
(left >= right || top >= bottom)
void inset(float dx, float dy) x좌표를 dx 만큼, y좌표를 dy 만큼 추가
void offset(float dx, float dy) 사각형의 좌우에 dx 만큼, 상하에 dy만큼 여백을 추가

 

+)

invalidate() 메서드는 UI 스레드에서만 호출하도록 한다. non-UI 스레드에서는 postInvalidate() 메서드를 호출할 것.

Comments