4

In need to round the corners of several widget in android, but changing the background to a drawable is no solution here.

Therefore I want to create a drawable which I can place on top of any ui element. Take a look at this image; I need the black part to be transparent and the white part to be solid.

Image

I only know how to create the negative (a rectangle with rounded corners) shape:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">


    <solid
        android:color="@color/colorForegroundTable"
        />

   <corners android:radius="10dp" />

    <padding
        android:left="20dp"
        android:top="10dp"
        android:right="20dp"
        android:bottom="10dp"    >
    </padding>

</shape>

Any ideas?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

3 Answers3

0

The answer at https://stackoverflow.com/a/64464686/505152 can help you out, you can set a clipping border to the views, it works very well:

fun setCorners() {

    val mOutlineProvider = object : ViewOutlineProvider() {
        override fun getOutline(view: View, outline: Outline) {

            val left = 0
            val top = 0
            val right = view.width
            val bottom = view.height
            val cornerRadiusDP = 16f
            val cornerRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, cornerRadiusDP, resources.displayMetrics).toInt()

            // all corners
            outline.setRoundRect(left, top, right, bottom, cornerRadius.toFloat())
        }
    }

    binding.linearlayoutSidebar.apply {
        outlineProvider = mOutlineProvider
        clipToOutline = true
    }
}

Went from:

enter image description here

to:

enter image description here

htafoya
  • 18,261
  • 11
  • 80
  • 104
-1

You could just make a 9-patch image with the corners and use that drawable.

sbirksted
  • 62
  • 2
  • Could work , I don't know why it god bad votes. The only drawback is that you need to create the 9-patch for each resolution. – htafoya Feb 28 '22 at 17:19
-3

You can use layer-list to mask shape

<layer-list>

<item>
    <shape android:shape="rectangle">
       <solid android:color="@android:color/white"/>
    </shape>
</item>

<item>
  <shape android:shape="rectangle">
      <solid android:color="@android:color/black"/>
      <corners android:radius="50dp"/>
  </shape>
</item>
</layer-list>
Vishal
  • 551
  • 3
  • 11