ShapeableImageView

Evan Chen
Evan Android Note
Published in
6 min readAug 6, 2020

隨著Material Design Component 1.2 正式版發佈,就來試試這次新增的ShapeableImageView。你可以用這個imageView做出下圖的形狀。

以往我們要為圖片加上圓角可能會直接用CardView來處理,而如果要變圓形圖片也蠻麻煩的,現在我們可以直接在Style設定。

先加入dependencies

implementation 'com.google.android.material:material:1.2.0'

新增一個 ShapeableImageView,app:shapeAppearanceOverlay指定用來調整形狀的Style。

<com.google.android.material.imageview.ShapeableImageView
android:id="@+id/imageView"
android:layout_width="100dp"
android:layout_height="100dp"
android:scaleType="centerCrop"
android:src="@mipmap/image"
app:shapeAppearanceOverlay="@style/roundedCorner" />

新增圓角Style

<!--圓角-->
<style name="roundedCorner" parent="">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">20dp</item>
</style>

cornerFamily=founded 表示圓角,cornerSize則是圓角的大小。這樣就完成一個4個角都變圓角的圖片了。

圓形

同樣cornerFamily=rounded,把cornerSize改成50%,就會變成圓形了。

<!--圓形-->
<style name="circle" parent="">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">50%</item>
</style>

切角

cornerFamily 改成cut。

<!--角-->
<style name="cutImageView" parent="">
<item name="cornerFamily">cut</item>
<item name="cornerSize">20dp</item>
</style>

菱形

cornerFamily同樣用cut,cornerSize改成50%,就會變成凌形了。

<!--菱形-->
<style name="cutImageView2" parent="">
<item name="cornerFamily">cut</item>
<item name="cornerSize">50%</item>
</style>

針對4個角

你可以指定調整4個角落的某一個,例如只在右上使用圓角。

<!--右上-->
<style name="topRightCorner" parent="">
<item name="cornerFamilyTopRight">rounded</item>
<item name="cornerSizeTopRight">50dp</item>
</style>

右上及右上使用cut

<!--右邊-->
<style name="rightCut" parent="">
<item name="cornerFamily">cut</item>
<item name="cornerSizeTopRight">50%</item>
<item name="cornerSizeBottomRight">50%</item>
</style>

最後,也可以在Activity上設定。

val radius = 50.0f
imageView.shapeAppearanceModel = imageView.shapeAppearanceModel
.toBuilder()
.setTopRightCorner(CornerFamily.ROUNDED, radius)
.setBottomLeftCorner(CornerFamily.ROUNDED, radius)
.build()

Github:
https://github.com/evanchen76/ShapeableImageViewSample

有興趣也可以看看Material Design 的Shape官方說明

https://material.io/design/shape/about-shape.html

https://material.io/develop/android/theming/shape

參考:

https://medium.com/google-design/material-components-for-android-1-2-0-is-now-available-aade483ed841

--

--