Android中的ShapeableImageView

效果如下:

preview

声明依赖项

在 app/build.gradle.kts 中的 dependencies 添加:

1
2
3
dependencies {
implementation("com.google.android.material:material:1.8.0")
}

除了 ShapeableImageView , Android Material 中还有很多其他有用的东西,以后接触到再慢慢记录。

添加 style

在 res/values/styles.xml 中添加:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="utf-8"?>
<resources>

<!-- 圆形图片 -->
<style name="circle_image">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">50%</item>
</style>

<!-- 圆角图片 -->
<style name="round_image">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">10dp</item>
</style>

</resources>

使用 ShapeableImageView

1
2
3
4
5
6
7
<com.google.android.material.imageview.ShapeableImageView
android:id="@+id/circle_image"
android:layout_width="64dp"
android:layout_height="64dp"
android:contentDescription="@null"
android:scaleType="centerCrop"
app:shapeAppearance="@style/circle_image" />

若要描边效果,则加上以下属性:

属性 作用
strokeColor 描边颜色
strokeWidth 描边宽度
padding strokeWidth的一半

效果:

circle_image

参考这篇文章