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

前端 未结 15 2371
后悔当初
后悔当初 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:12

    This is an old question, however I wanted to add my solution because it uses the native SDK without lots of custom code or hacky drawing. This solution is supported back to API 1.

    The way to do this properly is to create a path (as mentioned in other answers) however the previous answers seem to overlook the addRoundedRect function call that takes radii for each corner.

    Variables

    private val path = Path()
    private val paint = Paint()
    

    Setup Paint

    paint.color = Color.RED
    paint.style = Paint.Style.FILL
    

    Update Path with Size Changes

    Call this somewhere that isn't onDraw, such as onMeasure for a view or onBoundChange for a drawable. If it doesn't change (like this example) you could put this code where you set up your paint.

    val radii = floatArrayOf(
        25f, 25f, //Top left corner
        25f, 25f, //Top right corner
        0f, 0f,   //Bottom right corner
        0f, 0f,   //Bottom left corner
    )
    
    path.reset() //Clears the previously set path
    path.addRoundedRect(0f, 0f, 100f, 100f, radii, Path.Direction.CW)
    

    This code creates a 100x100 rounded rect with the top corners rounded with a 25 radius.

    Draw Path

    Call this in onDraw for a view or draw for a drawable.

    canvas.drawPath(path, paint)
    

提交回复
热议问题