Can anybody tell how to draw a line in Android, perhaps with an example?
Can anybody tell how to draw a line in Android, perhaps with an example?
If you're working with ConstraintLayout you need to define at least 2 constraints for the line to show up. Like this:
<View
android:layout_width="0dp"
android:layout_height="1dp"
android:background="@android:color/black"
app:layout_constraintEnd_toEndOf="@+id/someView1"
app:layout_constraintStart_toStartOf="@+id/someView2"
app:layout_constraintTop_toBottomOf="@+id/someView3" />
Though I defined 3 constraints.
If anyone can benefit from a simplified solution:
Point class not needed. Directly in MotionEvent.ACTION_MOVE move to the start X and Y coordinates that you get from MotionEvent.ACTION_DOWN. This method works better since we use drawPath instead of drawLine, which is less computationally intensive and therefore performs better.
class DrawingView(context: Context,
attributeSet: AttributeSet): View(context, attributeSet) {
private val mPaint = Paint()
private var mPath = Path()
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.drawPath(mPath, mPaint)
}
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
startX = event.x
startY = event.y
invalidate()
}
MotionEvent.ACTION_MOVE -> {
endX = event.x
endY = event.y
val path = Path()
path.moveTo(startX, startY) <- // Important!
path.lineTo(endX, endY)
mPath = path
invalidate()
}
}
return true
}
}