Android
 Computer >> コンピューター >  >> プログラミング >> Android

Androidで円形のImageViewに影と境界線を追加する方法【コード例付き】

はじめに

この記事では、AndroidアプリのImageViewに表示する画像を円形に切り取り、さらに白い境界線影(外枠)を追加する方法を、実際のコード例とともに段階的に解説します。

ポイントは、RoundedBitmapDrawableFactoryで生成できるRoundedBitmapDrawableを使って画像を円形化し、PaintCanvasを使って境界線や影を描画するところです。

手順1:新規プロジェクトを作成する

Android Studioを開き、メニューから「File」→「New Project」を選択して、必要な項目を入力し新しいプロジェクトを作成します。今回は空のアクティビティ(Empty Activity)で問題ありません。

手順2:レイアウトファイル(activity_main.xml)を編集する

res/layout/activity_main.xmlに以下のコードを記述します。画面中央にImageViewを配置し、右下に円形化を実行するボタンを配置しています。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="@+id/rl"
    android:padding="16dp"
    tools:context=".MainActivity">
    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>
    <Button
        android:id="@+id/btn_circular"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Circular It"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"/>
</RelativeLayout>

手順3:MainActivity.javaに処理を記述する

src/MainActivity.javaに以下のコードを追加します。ボタンがタップされると、元のBitmapをもとに白い境界線と薄いグレーの影を描画した円形画像を生成し、ImageViewにセットします。

package com.app.sample;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Resources mResources;
    private RelativeLayout mRelativeLayout;
    private Button mBTNCircular;
    private ImageView mImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = getApplicationContext();
        mResources = getResources();
        mRelativeLayout = (RelativeLayout) findViewById(R.id.rl);
        mImageView = (ImageView) findViewById(R.id.iv);
        mBTNCircular = (Button) findViewById(R.id.btn_circular);

        // リソースから元画像を読み込む
        final Bitmap srcBitmap = BitmapFactory.decodeResource(mResources, R.drawable.flower);
        mImageView.setImageBitmap(srcBitmap);

        mBTNCircular.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Paint paint = new Paint();
                int srcBitmapWidth = srcBitmap.getWidth();
                int srcBitmapHeight = srcBitmap.getHeight();
                int borderWidth = 25;   // 境界線の幅
                int shadowWidth = 10;   // 影の幅

                // 出力用Bitmapのサイズを計算
                int dstBitmapWidth = Math.min(srcBitmapWidth, srcBitmapHeight) + borderWidth * 2;
                Bitmap dstBitmap = Bitmap.createBitmap(dstBitmapWidth, dstBitmapWidth, Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(dstBitmap);
                canvas.drawColor(Color.WHITE);

                // 元画像を中央に描画
                canvas.drawBitmap(srcBitmap, (dstBitmapWidth - srcBitmapWidth) / 2, (dstBitmapWidth - srcBitmapHeight) / 2, null);

                // 白い境界線を描画
                paint.setStyle(Paint.Style.STROKE);
                paint.setStrokeWidth(borderWidth * 2);
                paint.setColor(Color.WHITE);
                canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, canvas.getWidth() / 2, paint);

                // 薄いグレーの影を描画
                paint.setColor(Color.LTGRAY);
                paint.setStrokeWidth(shadowWidth);
                canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, canvas.getWidth() / 2, paint);

                // 円形のDrawableに変換して ImageView に設定
                RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(mResources, dstBitmap);
                roundedBitmapDrawable.setCircular(true);
                roundedBitmapDrawable.setAntiAlias(true);
                mImageView.setImageDrawable(roundedBitmapDrawable);
            }
        });
    }
}

コードのポイント

  • borderWidth / shadowWidth:境界線と影の太さをピクセル単位で指定します。数値を変更すれば見た目を簡単に調整できます。
  • drawCircle():キャンバスの中心を基準に円を描くことで、境界線と影を同心円として重ねています。
  • setCircular(true):RoundedBitmapDrawableを完全な円形として表示するための設定です。setAntiAlias(true)を組み合わせることで、輪郭が滑らかな円になります。

手順4:AndroidManifest.xmlを確認する

Manifests/AndroidManifest.xmlには以下のようにMainActivityを宣言します。特別なパーミッションは不要です。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.app.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」アイコンをクリックします。デバイス選択画面で接続した端末を選択すると、実機の画面にアプリが表示されます。

初期状態では元画像(ここでは花の画像)がそのまま表示され、「Circular It」ボタンをタップすると、画像が白い境界線と影付きの円形に切り替わります。

Androidで円形のImageViewに影と境界線を追加する方法【コード例付き】

まとめ

このように、CanvasPaintで境界線・影を描き、RoundedBitmapDrawableで円形化するだけで、影と境界線付きの円形画像を簡単に実装できます。プロフィール画像など、円形アイコンを使いたい場面でぜひ活用してください。

  1. AndroidでImageViewの幅と高さを取得する方法【サンプルコード付き】

    この記事では、Androidアプリ開発において android.widget.ImageView の幅(width)と高さ(height)を取得する方法を、実際に動作するサンプルコードとともにステップごとに解説します。実装の全体像ImageViewのサイズを取得するには、getWidth() メソッドと getHeight() メソッドを使用します。ここでは、ボタンをタップしたときにImageViewのサイズを取得し、TextViewに結果を表示するシンプルなサンプルアプリを作成します。手順1:新しいプロジェクトを作成するAndroid Studioを起動し、メニューから「File」→「New

  2. AndroidアプリのImageViewで画像を読み込んで表示する方法を徹底解説

    この記事では、AndroidアプリにおいてImageViewを使って画像を読み込み、画面に表示する方法をステップごとに解説します。ボタンをタップすると表示中の画像が切り替わるシンプルなサンプルアプリを題材にしているので、ImageViewの基本的な使い方を学びたい初心者の方にもおすすめです。 手順1:Android Studioで新規プロジェクトを作成する まずはAndroid Studioを起動し、メニューから「File」→「New Project」を選択して新しいプロジェクトを作成します。プロジェクト名やパッケージ名など必要な項目を入力して、セットアップを完了させてください。 手順2:レイ