Re: note

技術的な知見やポエムなど役に立たない情報を書き連ねる場所

AndroidのCardViewを使って画像を丸くする

f:id:hik0leaf:20200418194817p:plain

アバター画像を丸く表示する場合、Picassoなどのtransformが良く使われますがコードを書く必要があり少し手間がかかります。代わりにCardViewを使うとXML上でプロパティを指定することで簡単に画像を丸くすることができます。

準備

まずCardViewが使えるようにするために build.gradle に以下の行を追加します。
※今回はAndroidXを使っています。

dependencies {
    implementation 'androidx.cardview:cardview:1.0.0'
}

AndroidXを使わない場合は、以下のリンクを参照してください。

developer.android.com

レイアウト

以下のレイアウトを参考にしてCardViewを追加します。画像を丸くするには cardCornerRadius プロパティを使います。値はCardViewサイズの半分を指定するとちょうど円にすることができます(正方形の場合)。

子要素には画像を表示するためのImageViewを入れてください。

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.cardview.widget.CardView
        android:layout_width="200dp"
        android:layout_height="200dp"
        app:cardCornerRadius="100dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" >

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            android:src="@drawable/test_image" />

    </androidx.cardview.widget.CardView>

</androidx.constraintlayout.widget.ConstraintLayout>

サンプルで使用した画像はこちらです。私が撮った写真です。 f:id:hik0leaf:20200418200325j:plain

Android Designer上(Android Studio 3.6.2)では残念ながらプレビューはされませんが気にせず進めてください。Android Studioがバージョンアップされればいずれプレビューできるかもしれません。

f:id:hik0leaf:20200418200843p:plain

結果

ビルドして実行すると以下のようになります。

f:id:hik0leaf:20200418201145p:plain


cardCornerRadius の値をCardViewの半分のサイズよりも小さい値を指定すると角丸に指定することができます。下の例では16dpを指定しました。

f:id:hik0leaf:20200418202444p:plain

まとめ

CardViewを使うと cardCornerRadius を指定するだけで簡単に画像を丸くすることができました。今回はImageViewを丸くしましたが、他のViewも子要素に入れることで丸くすることができます。