Curved Corner BottomSheet using Canvas and XML

Saurabh Pant
ProAndroidDev
Published in
3 min readMar 6, 2022

--

There are multiple ways of doing the same thing. You choose which way to go.

Image by New18

The article covers how can we create a bottom sheet with round corners via XML and Canvas separately. Let’s see what we’re going to build.

First, let’s take the XML approach which is very straightforward to use. We simply create a rectangle shape with top left and right corners with some radius as follows.

background_curved_corners.xml

Then set this shape as a background to our container layout as follows

dialog_curved_corners.xml

So far so good and we’re ready with our target. But we encounter an issue which you can easily spot in the image below.

Bottom sheet with round corners

We can see the black area outside of the curved corners. This issue we’ll fix at the end of this article. But for now let’s move on to our second approach which is using the canvas.

So how can we have the same shape if we try to do this via custom drawing. Well! That is also quite easy to achieve but require some understanding of custom view drawing on canvas. In case you want to read more about it you can check out this article of mine.

Now, we need to create a custom view with the same shape as our target. We’ll use LinearLayout as our main container here. Go ahead and create the class CurvedContainer.kt. as follows:

CurvedContainer.kt

What are we doing here? We’ll draw a path and paint the enclosed area of the path. Simple! Below image shows how the path actually looks like if we simply draw it using stroke/border.

path with style STROKE

The blue line indicates our path and the points indicates the position we’re drawing our path on, in a linear clockwise fashion. We’ll create the path once we know the size of our view i.e. in onSizeChanged function.

function onSizeChanged

It is evident that we’re drawing our path step by step from one point to other and finally completing the path to the point P1 from where we started. This way we get our curved shape. And once we’ve our path ready, we’ll draw it on our canvas in onDraw function as follows:

We’ll set this CurvedContainer.kt in our bottom sheet layout and the output will be the same as the XML approach output we saw above. We still have the gray area outside of our curved corners.

To address our issue, we’ll create a style as follows:

We’ll set this style to our bottom sheet dialog so that it won’t draw any color to our custom view by setting the color background to transparent.

BottomSheetContainer.kt

We now have our target hit. You can try the same and see how it works.

Hope it’ll help!

Until we meet again…Cheers!

--

--

App Developer (Native & Flutter) | Mentor | Writer | Youtuber @_zaqua | Traveller | Content Author & Course Instructor @Droidcon | Frontend Lead @MahilaMoney