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

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

    A Path#arcTo() version to draw the rounded side if the radius is half of the height.

    fun getPathOfRoundedRectF(
        rect: RectF,
        topLeftRadius: Float = 0f,
        topRightRadius: Float = 0f,
        bottomRightRadius: Float = 0f,
        bottomLeftRadius: Float = 0f
    ): Path {
        val tlRadius = topLeftRadius.coerceAtLeast(0f)
        val trRadius = topRightRadius.coerceAtLeast(0f)
        val brRadius = bottomRightRadius.coerceAtLeast(0f)
        val blRadius = bottomLeftRadius.coerceAtLeast(0f)
    
        with(Path()) {
            moveTo(rect.left + tlRadius, rect.top)
    
            //setup top border
            lineTo(rect.right - trRadius, rect.top)
    
            //setup top-right corner
            arcTo(
                RectF(
                    rect.right - trRadius * 2f,
                    rect.top,
                    rect.right,
                    rect.top + trRadius * 2f
                ), -90f, 90f
            )
    
            //setup right border
            lineTo(rect.right, rect.bottom - trRadius)
    
            //setup bottom-right corner
            arcTo(
                RectF(
                    rect.right - brRadius * 2f,
                    rect.bottom - brRadius * 2f,
                    rect.right,
                    rect.bottom
                ), 0f, 90f
            )
    
            //setup bottom border
            lineTo(rect.left + blRadius, rect.bottom)
    
            //setup bottom-left corner
            arcTo(
                RectF(
                    rect.left,
                    rect.bottom - blRadius * 2f,
                    rect.left + blRadius * 2f,
                    rect.bottom
                ), 90f, 90f
            )
    
            //setup left border
            lineTo(rect.left, rect.top + tlRadius)
    
            //setup top-left corner
            arcTo(
                RectF(
                    rect.left,
                    rect.top,
                    rect.left + tlRadius * 2f,
                    rect.top + tlRadius * 2f
                ),
                180f,
                90f
            )
    
            close()
    
            return this
        }
    }
    

提交回复
热议问题