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

Kotlin으로 안드로이드 ImageView 이미지 회전 구현하기 – 단계별 완벽 가이드

Kotlin으로 안드로이드 ImageView 이미지 회전하기

이 튜토리얼에서는 Kotlin을 활용해 안드로이드 앱에서 ImageView에 표시된 이미지를 지정한 각도만큼 회전시키는 방법을 소개합니다. 핵심은 단 한 줄의 코드, imageView.rotation = 90f라는 점입니다. 그럼 단계별로 차근차근 살펴보겠습니다.

1단계 — 새 프로젝트 만들기

Android Studio를 열고 File → New Project 메뉴로 이동한 뒤, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력합니다.

2단계 — 레이아웃 파일(activity_main.xml) 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면에는 회전할 이미지를 보여줄 ImageView와, 회전을 실행할 Button을 함께 배치했습니다.

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

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="600dp"
        android:src="@drawable/image" />

    <Button
        android:id="@+id/btnRotate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/imageView"
        android:layout_alignParentBottom="true"
        android:layout_centerInParent="true"
        android:text="Rotate View"
        android:textStyle="bold" />

</RelativeLayout>

3단계 — MainActivity.kt 작성

src/MainActivity.kt 파일에 다음 코드를 추가합니다. 버튼을 클릭하면 rotation 속성에 90f(90도)가 설정되어 이미지가 시계 방향으로 90도 회전합니다.

import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    lateinit var imageView: ImageView
    lateinit var btnRotate: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        imageView = findViewById(R.id.imageView)
        btnRotate = findViewById(R.id.btnRotate)
        btnRotate.setOnClickListener { imageView.rotation = 90f }
    }
}

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 아이콘 Kotlin으로 안드로이드 ImageView 이미지 회전 구현하기 – 단계별 완벽 가이드 을 클릭하세요. 실행 옵션 목록에서 본인의 모바일 기기를 선택하면 앱이 실행됩니다.

버튼을 누르기 전의 초기 화면입니다.

Kotlin으로 안드로이드 ImageView 이미지 회전 구현하기 – 단계별 완벽 가이드

버튼을 클릭하면 아래 화면처럼 이미지가 90도 회전한 것을 확인할 수 있습니다.

Kotlin으로 안드로이드 ImageView 이미지 회전 구현하기 – 단계별 완벽 가이드

추가 팁

rotation 값은 도(degree) 단위이며, 양수는 시계 방향, 음수는 반시계 방향으로 회전합니다. 45f, 180f 등 원하는 각도로 자유롭게 변경할 수 있고, 부드러운 회전 애니메이션이 필요하다면 imageView.animate().rotation(90f)ObjectAnimator를 활용하는 것도 좋은 방법입니다.