Search code examples
androidcanvas

android canvas draw line inside a rect


How can I draw this black line with 45 degree inside the red rect. if the line's width is too large , it will outside the rect showing as blue, how can I resolve this?

private fun createRect(x: Float, y: Float, w: Int, h: Int) = RectF(
    x, y, (x + w), (y + h)
)

fun drawRoundRect(c: Canvas, p: Paint, x: Float, y: Float, w: Int, h: Int) {
    c.drawRoundRect(createRect(x, y, w, h), cornerSize, cornerSize, p)
}

fun drawRectWithLine(
    c: Canvas, frameP: Paint, disablePaint: Paint, x: Float, y: Float, w: Int, h: Int
) {
    drawRoundRect(c, frameP, x, y, w, h)
    c.drawLine(x, y, x + w, y + h, disablePaint)
}

enter image description here


Solution

  • you may use canvas.clipRect(...) drawing order is

    canvas.save()
    canvas.clipRect(...)
    canvas.drawRect(...)
    canvas.drawLine(...)
    canvas.restore()