真ん丸や角丸の画像を作る方法としてPiccasoなどのライブラリを使う方法1や、手軽な方法としてCardViewを用いたやり方2などがありますが、Material Components 1.2.0に追加されたShapeableImageView
を使ったやり方を紹介してみます。
下のような画像を手軽に作成できます。
準備
Material Components 1.2.0を追加しておきます。
dependencies {
implementation "com.google.android.material:material:1.2.0"
}
使い方
使い方としては、styleを定義してShapeableImageView
のapp:shapeAppearanceOverlay
属性に指定してやるだけでOKです。以下で詳しく見ていきます。
真ん丸
styles.xml
に以下を追加。
cornerFamily
にrounded
、cornerSize
に50%を指定してあります。
<style name="circleImageView" parent="">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">50%</item>
</style>
あとはレイアウトファイルにShapeableImageView
を配置してapp:shapeAppearanceOverlay
属性に上記のスタイルを指定してやります。
<com.google.android.material.imageview.ShapeableImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:adjustViewBounds="true"
android:src="@drawable/ic_droid"
app:shapeAppearanceOverlay="@style/circleImageView" />
![circle.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F658739%2F2406e153-3d8a-acc1-0d2a-59c9b6fe3725.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=bcbd87d969248935e63fc69f3b47f44a)
角丸
cornerSize
を調整してやれば角丸にできます。
今回は24%にしてみました。
<style name="roundedCornersImageView" parent="">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">24%</item>
</style>
![cornerRounded.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F658739%2F5eff2272-e9fb-8d0e-e47f-c9d2b9d6af54.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=61db3277a28ff50341c422c8e1e9acad)
ひし形
cornerFamily
にcut
を指定し、cornerSize
を50%にすればひし形にできます。
<style name="diamondImageView" parent="">
<item name="cornerFamily">cut</item>
<item name="cornerSize">50%</item>
</style>
![diamond.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F658739%2F8ff913a5-6493-b504-c7f3-9b11ef0da5f4.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=8722db96f985da063f205c7ec38d0337)
部分的に適応
四隅の一部のみを変えることも可能です。
例えば左上をround、右下をcutにするには以下のように指定してやります。
指定できる属性名についてはhttps://material.io/develop/android/theming/shapeに載ってます。
<style name="mixImageView" parent="">
<item name="cornerFamilyTopLeft">rounded</item>
<item name="cornerFamilyBottomRight">cut</item>
<item name="cornerSizeTopLeft">28%</item>
<item name="cornerSizeBottomRight">24%</item>
</style>
![mix.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F658739%2F08dc68b4-cc28-9b3f-e271-11b3b9d4e418.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=b4d9ac4be3477a63978b282c917743d2)
手軽に真ん丸や角丸などの画像を作成できました!
以上です。
参考にしたサイト
How to use the ShapeableImageView
Material Components: ShapeableImageViewで丸く切り抜かれた画像を表示する