问题描述
我有这个问题的答案,但我在寻找它时花费了太多时间。 这就是我创建这个问题的原因,因此对其他人来说会更容易。
你不能像通常的视图那样用形状@drawable 来圆化图像的角。 这就是为什么您需要对 Image 内部代码进行一些更改。
解决方法
这是使用 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>
完整的舍入输出:
这就是快乐编码:)
,您需要先定义形状:
<?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,(view.height+48f).toInt(),48f)