이 튜토리얼에서는 안드로이드 앱에서 사용자의 손가락 움직임을 따라 부드러운 선을 그리는 방법을 단계별로 알아봅니다. Bitmap, Canvas, 그리고 터치 이벤트(MotionEvent)를 활용하면 간단한 드로잉 앱을 손쉽게 만들 수 있습니다.
1단계 – 새 프로젝트 생성
Android Studio를 실행한 뒤 File → New Project 메뉴로 이동하고, 필요한 항목을 모두 입력하여 새 프로젝트를 생성합니다.
2단계 – 레이아웃 파일 작성
res/layout/activity_main.xml에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:src="@drawable/ic_launcher_foreground" />
</RelativeLayout>3단계 – MainActivity 작성
src/MainActivity.java에 다음 코드를 추가합니다.
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity implements View.OnTouchListener {
ImageView imageView;
Bitmap bitmap;
Canvas canvas;
Paint paint;
float downX = 0, downY = 0, upX = 0, upY = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = this.findViewById(R.id.imageView);
Display currentDisplay = getWindowManager().getDefaultDisplay();
float dw = currentDisplay.getWidth();
float dh = currentDisplay.getHeight();
bitmap = Bitmap.createBitmap((int) dw, (int) dh,
Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
paint = new Paint();
paint.setColor(Color.BLACK);
imageView.setImageBitmap(bitmap);
imageView.setOnTouchListener(this);
}
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
downX = event.getX();
downY = event.getY();
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
upX = event.getX();
upY = event.getY();
canvas.drawLine(downX, downY, upX, upY, paint);
imageView.invalidate();
break;
case MotionEvent.ACTION_CANCEL:
break;
default:
break;
}
return true;
}
}코드 동작 원리
- ACTION_DOWN: 손가락이 화면에 닿는 순간 시작 좌표(downX, downY)를 저장합니다.
- ACTION_UP: 손가락을 뗄 때 끝 좌표(upX, upY)를 저장하고, canvas.drawLine()로 두 점 사이에 선을 그립니다.
- invalidate(): ImageView를 다시 그려 변경된 비트맵을 화면에 반영합니다.
4단계 – 매니페스트 설정
androidManifest.xml에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>앱 실행하기
실제 안드로이드 기기를 컴퓨터에 연결했다고 가정하고 앱을 실행해 보겠습니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run(실행) 아이콘을 클릭하세요. 기기 목록에서 자신의 모바일 기기를 선택하면, 해당 기기 화면에 아래와 같은 결과가 표시됩니다.

더 부드러운 선을 위한 팁
선을 더욱 매끄럽게 표현하려면 Paint 객체에 안티앨리어싱 옵션과 스트로크 설정을 추가하는 것이 좋습니다.
paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(Color.BLACK); paint.setStrokeWidth(8f); paint.setStrokeCap(Paint.Cap.ROUND);
또한 ACTION_MOVE 이벤트가 발생할 때마다 이전 좌표에서 현재 좌표까지 선을 이어 그리면, 손가락 움직임을 실시간으로 따라가는 자연스러운 드로잉 효과를 구현할 수 있습니다.
참고로 getWindowManager().getDefaultDisplay()와 getWidth()/getHeight()는 현재 deprecated된 API이므로, 최신 프로젝트에서는 WindowManager의 getCurrentWindowMetrics() 또는 Resources.getSystem().getDisplayMetrics()를 사용하는 것이 권장됩니다.