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

Kotlin으로 안드로이드 이미지 위에 텍스트 그리기: 단계별 완벽 가이드

이 글에서는 Kotlin을 사용해 안드로이드 앱에서 이미지 위에 텍스트를 표시(그리기)하는 방법을 단계별로 알아봅니다. RelativeLayout 안에 ImageView와 TextView를 함께 배치하면, 복잡한 커스텀 뷰 없이도 간단하게 이미지 위에 원하는 문구를 얹을 수 있습니다.

1단계: 새 프로젝트 생성

Android Studio를 실행하고 File → New Project 메뉴로 이동한 뒤, 필요한 모든 정보를 입력하여 새 프로젝트를 생성합니다. 언어는 Kotlin으로 선택하세요.

2단계: 레이아웃 파일 작성 (res/layout/activity_main.xml)

아래 코드를 activity_main.xml에 추가합니다. ImageView가 배경 이미지를 담당하고, TextView는 화면 하단에 정렬되어 이미지 위에 텍스트를 표시합니다.

<?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"
    android:padding="8dp"
    tools:context=".MainActivity">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/image" />

<TextView
    android:id="@+id/text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="16sp"
    android:padding="4dp"
    android:textSize="24sp"
    android:textStyle="bold|italic" />

</RelativeLayout>

3단계: MainActivity.kt 작성

src/MainActivity.kt 파일에 아래 코드를 추가합니다. findViewById로 TextView를 가져온 뒤, 표시할 문자열과 텍스트 색상을 지정합니다.

import android.graphics.Color
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"

        val textView: TextView = findViewById(R.id.text)
        textView.text = "Into the wild!"
        textView.setTextColor(Color.WHITE)
    }
}

4단계: AndroidManifest.xml 확인

androidManifest.xml에는 아래와 같이 기본 설정이 포함되어 있어야 합니다.

<?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 Studio에서 프로젝트의 액티비티 파일 중 하나를 열고, 상단 툴바의 Run 아이콘을 클릭하세요. 실행 옵션에서 연결된 모바일 기기를 선택하면, 해당 기본 화면에 이미지 위에 흰색 굵은 기울임꼴 텍스트가 표시되는 것을 확인할 수 있습니다.