Cloud Town
Cloud Town

Reputation: 83

How to draw a line with rounded ends on a canvas in Android

Okay so searched for this extensively but there're no clear examples of how to draw a line with rounded ends. The code below draws the line but it's not rounded at either end. I also searched for what Android Studio says when I hover over drawLine: Style is not applied since it's framed. Someone seemed to have come up with the answer but they didn't post their code. Anyway is there a way to get a line to have rounded ends? If not, how can I convert the drawLine method with the drawPath method. I'm not sure how to use drawPath properly to draw a line that is straight and follows my finger (or mouse in the emulator).

class DrawingView(context: Context,
                  attributeSet: AttributeSet): View(context, attributeSet) {

    val mPaint = Paint()
    var startX = 0f
    var startY = 0f
    var endX = 0f
    var endY = 0f
    init {
        mPaint.color = Color.GREEN
        mPaint.style = Paint.Style.STROKE
        mPaint.strokeJoin = Paint.Join.ROUND
        mPaint.strokeCap = Paint.Cap.ROUND
        mPaint.strokeWidth = 50f

    }
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawLine(startX, startY, endX, endY, mPaint)
    }
    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                startX = event.x
                startY = event.y
                endX = event.x
                endY = event.y
                invalidate()
            }
            MotionEvent.ACTION_MOVE -> {
                endX = event.x
                endY = event.y
                invalidate()
            }
            MotionEvent.ACTION_UP -> {
                endX = event.x
                endY = event.y
                invalidate()
            }
        }
        return true
    }
}

Upvotes: 2

Views: 1219

Answers (1)

Dharmender Manral
Dharmender Manral

Reputation: 1520

Try with the following code.

   var paint = Paint()
    paint.apply {
        color = color
        strokeWidth = size
        isDither = true
        style = Paint.Style.STROKE
        strokeJoin = Paint.Join.ROUND
        strokeCap = Paint.Cap.ROUND
        pathEffect = CornerPathEffect(10F)
        isAntiAlias = true
    }

Upvotes: 3

Related Questions