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

Android 앱에서 둥근 모서리 ImageView 만드는 방법 (단계별 코드 예제)

이 튜토리얼에서는 BitmapShaderCanvas를 활용해 Android 앱에서 모서리가 둥근(rounded corners) ImageView를 구현하는 방법을 단계별로 살펴봅니다.

구현 단계

1단계 – 새 프로젝트 생성

Android Studio를 실행하고 File → New Project 메뉴로 이동한 뒤, 새 프로젝트 생성에 필요한 모든 정보를 입력하여 프로젝트를 만듭니다.

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

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.

<?xml version = "1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="fill_parent"
        android:layout_margin="10dp"
        android:layout_height="fill_parent" />
    </LinearLayout>

3단계 – MainActivity.java 코드 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다. 핵심 로직은 원본 비트맵 위에 BitmapShader를 적용한 Paint 객체로 drawRoundRect()를 호출하여 둥근 모서리의 새 비트맵을 그려내는 방식입니다.

package com.example.sample;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView=(TextView) findViewById(R.id.textView);
        textView.setTextColor(Color.RED);
        textView.setTextSize(20);
        ImageView mimageView=(ImageView) findViewById(R.id.imageView);
        Bitmap mbitmap=((BitmapDrawable) getResources().getDrawable(R.drawable.cat)).getBitmap();
        Bitmap imageRounded=Bitmap.createBitmap(mbitmap.getWidth(), mbitmap.getHeight(), mbitmap.getConfig());
        Canvas canvas=new Canvas(imageRounded);
        Paint mpaint=new Paint();
        mpaint.setAntiAlias(true);
        mpaint.setShader(new BitmapShader(mbitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
        canvas.drawRoundRect((new RectF(0, 0, mbitmap.getWidth(), mbitmap.getHeight())), 100, 100, mpaint); // Round Image Corner 100 100 100 100
        mimageView.setImageBitmap(imageRounded);
    }
}

위 코드에서 drawRoundRect()의 마지막 두 인자인 100, 100은 각각 X축·Y축 방향의 모서리 반지름(radius) 값입니다. 이 숫자를 조절하면 곡률의 정도를 자유롭게 변경할 수 있습니다.

4단계 – AndroidManifest.xml 설정

app/manifests/AndroidManifest.xml 파일에 아래 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.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 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭하세요. 실행 옵션에서 연결된 모바일 기기를 선택하면, 해당 기기에 아래와 같이 모서리가 둥근 이미지가 표시되는 것을 확인할 수 있습니다.

Android 앱에서 둥근 모서리 ImageView 만드는 방법 (단계별 코드 예제)

참고: 더 간편한 대안 방법들

직접 비트맵을 처리하는 방식 외에도 최신 Android 개발에서는 다음과 같은 방법을 활용하면 더욱 간편하게 둥근 모서리를 구현할 수 있습니다.

  • CardView 활용: cardCornerRadius 속성을 지정한 CardView 안에 ImageView를 배치하면 XML만으로 둥근 모서리를 적용할 수 있습니다.
  • ShapeableImageView 활용: Material Components 라이브러리의 ShapeableImageView를 사용하면 shapeAppearanceOverlay 스타일로 모서리 곡률을 세밀하게 제어할 수 있습니다.