How to draw a line in android

前端 未结 15 1972
野趣味
野趣味 2020-11-22 06:27

Can anybody tell how to draw a line in Android, perhaps with an example?

15条回答
  •  故里飘歌
    2020-11-22 07:19

    There are two main ways you can draw a line, by using a Canvas or by using a View.

    Drawing a Line with Canvas

    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:

    canvas.drawLine

    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);
    }
    

    Drawing a Line with View

    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:

    drawing a line with a view in xml layout

    And here is the complete xml layout for that:

    
    
    
    
    
    
    
    
    
    
    
        
    
        
    
        
    
    
    
    

提交回复
热议问题