只有底部或顶部圆角的ImageView

6

我对这个问题有答案,但在搜索答案时花费了太多时间。 这就是为什么我创建了这个问题,以便其他人更容易找到答案。

通常情况下,您不能像处理常规View一样使用形状@drawable来圆角化图像。 因此,您需要在代码中对图像进行一些更改。


https://dev59.com/r1IH5IYBdhLWcg3wh_Sn#59430153 - Gabriele Mariotti
2个回答

16

这是另一种使用 Material Design 的方法: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>

全圆输出:

enter image description here

就是这样,愉快地编程吧:).


3
你之前的答案在哪里呢?:) 如果你有材料设计,这种方法会更好。 - Andrey Kijonok
我在等待你的问题 :P。是的,Material Design 是一个很好的方式。 - Ali

1

首先,您需要定义形状:

<?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"/>

然后在您的活动中编写以下代码,以添加底部圆角。

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)

只有在API级别31或更高级别上才能使用clipToOutline - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接