How to use android canvas to draw a Rectangle with only topleft and topright corners round?

前端 未结 15 2421
后悔当初
后悔当初 2020-11-29 01:58

I found a function for rectangles with all 4 corners being round, but I want to have just the top 2 corners round. What can I do?

canvas.drawRoundRect(new Re         


        
15条回答
  •  孤独总比滥情好
    2020-11-29 02:21

    I achieved this by following the below steps.

    These are the pre-requisites for the rounded rectangle to look neat

    • The radius of the edges have to be equal to the (height of the rectangle / 2). This is because if its any different value then the place where the curve meets straight line of the rectangle will not be

    Next is the steps to draw the rounded rectangle.

    • First we draw 2 circles on the left and right side, with the radius = height of rectange / 2

    • Then we draw a rectangle between these circles to get the desired rounded rectangle.

    I am posting the code below

    private void drawRoundedRect(Canvas canvas, float left, float top, float right, float bottom) {
        float radius = getHeight() / 2;
        canvas.drawCircle(radius, radius, radius, mainPaint);
        canvas.drawCircle(right - radius, radius, radius, mainPaint);
        canvas.drawRect(left + radius, top, right - radius, bottom, mainPaint);
    }
    

    Now this results in a really nice rounded rectangle like the one shown below

提交回复
热议问题