Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Kotlin으로 안드로이드 화면에 선 그리기: Canvas 활용 단계별 가이드

이 튜토리얼에서는 Kotlin을 사용해 Android 앱 화면에 선(line)을 그리는 방법을 단계별로 살펴봅니다. BitmapCanvas 객체를 활용하면 별도의 커스텀 뷰를 만들지 않고도 간단하게 도형을 그릴 수 있습니다.

1단계: 새 프로젝트 생성

Android Studio에서 File ⇒ New Project로 이동해 새 프로젝트를 만들고, 필요한 모든 정보를 입력합니다. 'Empty Activity' 템플릿을 선택하면 이 예제를 바로 따라 할 수 있습니다.

2단계: activity_main.xml 레이아웃 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 중앙에는 선이 그려질 ImageView를, 하단에는 'Draw Line' 버튼을 배치했습니다.

<?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:id="@+id/relativeLayout"
    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="wrap_content"
        android:layout_centerInParent="true" />
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="70dp"
        android:text="Draw Line" />
</RelativeLayout>

3단계: MainActivity.kt 구현

src/MainActivity.kt 파일에 다음 코드를 추가합니다. 버튼을 클릭하면 Bitmap 위에 Canvas로 빨간색 선을 그린 뒤, 완성된 이미지를 ImageView에 표시하는 구조입니다.

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
    lateinit var button: Button
    lateinit var imageView: ImageView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        button = findViewById(R.id.button)
        imageView = findViewById(R.id.imageView)
        button.setOnClickListener {
            val bitmap = Bitmap.createBitmap(10, 700, Bitmap.Config.ARGB_8888)
            val canvas = Canvas(bitmap)
            canvas.drawColor(Color.RED)
            val paint = Paint()
            paint.color = Color.RED
            paint.style = Paint.Style.STROKE
            paint.strokeWidth = 8F
            paint.isAntiAlias = true
            val offset = 50
            canvas.drawLine(
            offset.toFloat(), (canvas.height / 2).toFloat(), (canvas.width - offset).toFloat(),  (canvas.height /
            2).toFloat(), paint)
            imageView.setImageBitmap(bitmap)
        }
    }
}

핵심 코드 설명

  • Bitmap.createBitmap() : 선을 그릴 캔버스의 크기(10×700px)와 색상 형식(ARGB_8888)을 지정해 비트맵을 생성합니다.
  • Paint 설정 : 색상(RED), 스타일(STROKE), 선 두께(8F), 안티앨리어싱(true)을 지정해 경계가 부드러운 선을 만듭니다.
  • canvas.drawLine() : 시작점과 끝점의 x·y 좌표를 지정해 수평선을 그립니다. offset 값(50)으로 양쪽 끝에 여백을 둡니다.

4단계: AndroidManifest.xml 설정

androidManifest.xml 파일에 아래 코드가 올바르게 들어가 있는지 확인합니다. MainActivity가 LAUNCHER 인텐트 필터로 등록되어 있어야 앱이 정상적으로 실행됩니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.q11">
    <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 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘Kotlin으로 안드로이드 화면에 선 그리기: Canvas 활용 단계별 가이드을 클릭하고 목록에서 자신의 모바일 기기를 선택하세요.

앱이 실행되면 'Draw Line' 버튼을 눌렀을 때 화면 중앙의 ImageView에 빨간색 가로 선이 나타나는 것을 확인할 수 있습니다.

Kotlin으로 안드로이드 화면에 선 그리기: Canvas 활용 단계별 가이드