ImageView with only bottom or top corners rounded
Asked Answered
Z

2

7

I have answer on this question, but I spend too much time while searching for it. That's why I created this question, so it would be easier for others.

You can't just round image corners with shape @drawable like usual View. That's why you need to make some changes to Image inside code.

Zeigler answered 10/2, 2021 at 13:39 Comment(1)
#59249390Greybeard
D
18

Here is the another way to do this using Material Design ShapeableImageView

Create one theme for shape and 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>

Now add ShapeableImageView in XML:

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

I you want to full rounded ShapeableImageView:

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

Full Rounded Output:

enter image description here

That's it Happy Coding :).

Dierdre answered 10/2, 2021 at 14:5 Comment(2)
Where was your answer before?:) This approach is better if you have material design.Zeigler
I'm waiting for your question :P. Yes material design is good way.Dierdre
Z
1

You need to define shape firstly:

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

Then use this shape as ImageView background:

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

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

And then in your activity write this code to add bottom rounded corners

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

If you want top corners to be rounded use:

outline?.setRoundRect(0, 0, view!!.width, (view.height+48f).toInt(), 48f)
Zeigler answered 10/2, 2021 at 13:39 Comment(1)
You can use clipToOutline only in API level 31 or higherAttestation

© 2022 - 2024 — McMap. All rights reserved.