Can anybody tell how to draw a line in Android, perhaps with an example?
There are two main ways you can draw a line, by using a Canvas
or by using a View
.
From the documentation we see that we need to use the following method:
drawLine (float startX, float startY, float stopX, float stopY, Paint paint)
Here is a picture:
The Paint
object just tells Canvas
what color to paint the line, how wide it should be, and so on.
Here is some sample code:
private Paint paint = new Paint();
....
private void init() {
paint.setColor(Color.BLACK);
paint.setStrokeWidth(1f);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
startX = 20;
startY = 100;
stopX = 140;
stopY = 30;
canvas.drawLine(startX, startY, stopX, stopY, paint);
}
If you only need a straight horizontal or vertical line, then the easiest way may be to just use a View
in your xml layout file. You would do something like this:
Here is a picture with two lines (one horizontal and one vertical) to show what it would look like:
And here is the complete xml layout for that: