仅底部或顶部圆角的 ImageView

ImageView with only bottom or top corners rounded

这个问题我有答案,但是我花了太多时间去寻找它。 这就是我创建这个问题的原因,这样对其他人来说会更容易。

您不能像通常的 View 那样只使用形状为 @drawable 的圆角图像。 这就是为什么您需要对 Image inside 代码进行一些更改。

你需要先定义形状:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners
        android:bottomLeftRadius="8dp"
        android:bottomRightRadius="8dp"
        android:topLeftRadius="0dp"
        android:topRightRadius="0dp" />
</shape>

然后使用这个形状作为ImageView背景:

<ImageView
      android:id="@+id/img"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"

      android:background="@drawable/rounded"
      android:src="@drawable/image"/>

然后在你的activity中写下这段代码来添加底部圆角

img.outlineProvider = object : ViewOutlineProvider() {
    override fun getOutline(view: View?, outline: Outline?) {
            val corner = 48f
            outline?.setRoundRect(0, -corner.toInt(), view!!.width, view.height,corner)
        }
    }
img.clipToOutline = true

如果您希望顶角变圆,请使用:

outline?.setRoundRect(0, 0, view!!.width, (view.height+48f).toInt(), 48f)

这是使用 Material 设计 ShapeableImageView

的另一种方法

为形状创建一个主题 cornerFamily

<style name="ImageView.Corner" parent="">
        <item name="cornerSizeTopRight">8dp</item>
        <item name="cornerSizeTopLeft">8dp</item>
        <item name="cornerSizeBottomLeft">0dp</item>
        <item name="cornerSizeBottomRight">0dp</item>
        <item name="cornerFamily">rounded</item>
    </style>

现在在 XML 中添加 ShapeableImageView:

<com.google.android.material.imageview.ShapeableImageView
     android:layout_width="75dp"
     android:layout_height="75dp"
     app:layout_constraintBottom_toBottomOf="parent"
     app:layout_constraintStart_toStartOf="parent"
     app:layout_constraintTop_toTopOf="parent"
     app:srcCompat="@drawable/temp_product_image"
     app:shapeAppearanceOverlay="@style/ImageView.Corner"/>

我想要全圆角的 ShapeableImageView:

<style name="ImageView.Round" parent="">
  <item name="cornerSize">50%</item>
</style>

全舍入输出:

就是这样快乐的编码:)。