如何在android中画一条线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3616676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 11:00:07  来源:igfitidea点击:

How to draw a line in android

android

提问by mohan

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

谁能告诉如何在Android中画一条线,也许举个例子?

回答by Janusz

If you want to have a simple Line in your Layout to separate two views you can use a generic View with the height and width you want the line to have and a set background color.

如果你想在你的 Layout 中有一个简单的 Line 来分隔两个视图,你可以使用一个通用的 View ,它具有你希望线条具有的高度和宽度以及设置的背景颜色。

With this approach you don't need to override a View or use a Canvas yourself just simple and clean add the line in xml.

使用这种方法,您不需要覆盖视图或自己使用画布,只需简单而干净地在 xml 中添加该行。

<View
 android:layout_width="match_parent"
 android:layout_height="1dp"
 android:background="@android:color/black" />

The example code I provided will generate a line that fills the screen in width and has a height of one dp.

我提供的示例代码将生成一条宽度填充屏幕且高度为 1 dp 的线。

If you have problems with the drawing of the line on small screens consider to change the height of the line to px. The problem is that on a ldpi screen the line will be 0.75 pixel high. Sometimes this may result in a rounding that makes the line vanish. If this is a problem for your layout define the width of the line a ressource file and create a separate ressource file for small screens that sets the value to 1px instead of 1dp.

如果在小屏幕上绘制线条有问题,请考虑将线条的高度更改为 px。问题在于,在 ldpi 屏幕上,该行将是 0.75 像素高。有时这可能会导致四舍五入,使线条消失。如果这是您的布局的问题,请定义资源文件的行宽,并为小屏幕创建单独的资源文件,将值设置为 1px 而不是 1dp。

This approach is only usable if you want horizontal or vertical lines that are used to divide layout elements. If you want to achieve something like a cross that is drawn into an image my approach will not work.

此方法仅在您想要用于划分布局元素的水平或垂直线时可用。如果您想实现诸如绘制到图像中的十字架之类的东西,我的方法将不起作用。

回答by DonGru

This one draws 2 lines which form a cross on the top left of the screen:

这个画了两条线,在屏幕的左上角形成一个十字:

DrawView.java

绘制视图

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;

public class DrawView extends View {
    Paint paint = new Paint();

    private void init() {
        paint.setColor(Color.BLACK);
    }

    public DrawView(Context context) {
        super(context);
        init();
    }

    public DrawView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public DrawView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    @Override
    public void onDraw(Canvas canvas) {
            canvas.drawLine(0, 0, 20, 20, paint);
            canvas.drawLine(20, 0, 0, 20, paint);
    }

}

The activity to start it:

启动它的活动:

StartDraw.java

开始绘图

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;

public class StartDraw extends Activity {
    DrawView drawView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        drawView = new DrawView(this);
        drawView.setBackgroundColor(Color.WHITE);
        setContentView(drawView);

    }
}

回答by Suragch

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

您可以通过两种主要方式绘制线条,使用 aCanvas或使用 a View

Drawing a Line with Canvas

用画布画一条线

From the documentationwe 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

canvas.drawLine

The Paintobject just tells Canvaswhat color to paint the line, how wide it should be, and so on.

Paint物体只是告诉Canvas什么颜色漆线,应该有多宽,等等。

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 Viewin your xml layout file. You would do something like this:

如果您只需要一条水平或垂直的直线,那么最简单的方法可能是View在您的 xml 布局文件中使用 a 。你会做这样的事情:

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@android:color/black" />

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

用xml布局中的视图画一条线

And here is the complete xml layout for that:

这是完整的 xml 布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:text="TextView1 in vertical linear layout" />

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@android:color/black" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:text="TextView2 in vertical linear layout" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:padding="10dp"
        android:text="TextView3 in horizontal linear layout" />

    <View
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:background="@android:color/black" />

    <TextView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:padding="10dp"
        android:text="TextView4 in horizontal linear layout" />
</LinearLayout>

</LinearLayout>

回答by Hema

You can draw multiple straight lines on view using Finger paint example which is in Developer android. example link

您可以使用开发人员 android 中的手指绘画示例在视图上绘制多条直线。 示例链接

Just comment: mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);You will be able to draw straight lines.

只是评论:mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);您将能够绘制直线。

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;

public class JoinPointsActivity extends Activity  {
    /** Called when the activity is first created. */
    Paint mPaint;
    float Mx1,My1;
    float x,y;
    @Override

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // setContentView(R.layout.main);
        MyView view1 =new MyView(this);
        view1.setBackgroundResource(R.drawable.image_0031_layer_1);
        setContentView(view1);


        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setColor(0xFFFF0000);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
       // mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeWidth(10);

    }

    public class MyView extends View {

        private static final float MINP = 0.25f;
        private static final float MAXP = 0.75f;

      private Bitmap  mBitmap;
        private Canvas  mCanvas;
        private Path    mPath;
       private Paint   mBitmapPaint;

        public MyView(Context c) {
            super(c);

            mPath = new Path();
          mBitmapPaint = new Paint(Paint.DITHER_FLAG);
        }

        @Override
       protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            super.onSizeChanged(w, h, oldw, oldh);
            mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            mCanvas = new Canvas(mBitmap);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            canvas.drawColor(0xFFAAAAAA);
           // canvas.drawLine(mX, mY, Mx1, My1, mPaint);
           // canvas.drawLine(mX, mY, x, y, mPaint);
            canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
            canvas.drawPath(mPath, mPaint);

        }

        private float mX, mY;
        private static final float TOUCH_TOLERANCE = 4;

        private void touch_start(float x, float y) {
            mPath.reset();
            mPath.moveTo(x, y);
            mX = x;
            mY = y;
        }
        private void touch_move(float x, float y) {
            float dx = Math.abs(x - mX);
            float dy = Math.abs(y - mY);
            if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
               // mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
                mX = x;
                mY = y;
            }
        }
        private void touch_up() {
            mPath.lineTo(mX, mY);
            // commit the path to our offscreen
            mCanvas.drawPath(mPath, mPaint);
            // kill this so we don't double draw
            mPath.reset();
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            float x = event.getX();
            float y = event.getY();

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    touch_start(x, y);
                    invalidate();
                    break;
                case MotionEvent.ACTION_MOVE:
                    touch_move(x, y);
                    invalidate();
                    break;
                case MotionEvent.ACTION_UP:
                    touch_up();
               //   Mx1=(int) event.getX();
                 //  My1= (int) event.getY();
                   invalidate();
                    break;
            }
            return true;
        }
    }

}

回答by vinay

package com.example.helloandroid;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;

public class HelloAndroid2Activity extends Activity {
    /** Called when the activity is first created. */
DrawView drawView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    drawView = new DrawView(this);
    drawView.setBackgroundColor(Color.WHITE);
    setContentView(drawView);
}
class DrawView extends View {
        Paint paint = new Paint();

        public DrawView(Context context) {
            super(context);
            paint.setColor(Color.BLUE);
        }
        @Override
        public void onDraw(Canvas canvas) {
             super.onDraw(canvas);
                canvas.drawLine(10, 20, 30, 40, paint);
                canvas.drawLine(20, 10, 50, 20, paint);

        }
}
}

回答by Mohanraj

for horizontal line on the layout :

对于布局上的水平线:

 <View
            android:id="@+id/View03"
            android:layout_width="fill_parent"
            android:layout_height="5dip"
            android:background="#0f0" />

for vertical line on the layout :

对于布局上的垂直线:

<View
        android:id="@+id/View04"
        android:layout_width="5dip"
        android:layout_height="fill_parent"
        android:background="#0f0" />

回答by shreedhar bhat

Simple one

简单的

 <TextView
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="#c0c0c0"
    android:id="@+id/your_id"
    android:layout_marginTop="160dp" />

回答by user712051

canvas.drawLine(10, 10, 90, 10, paint);
canvas.drawLine(10, 20, 90, 20, paint);

This will create a straight horizontal line, hope it helps!.

这将创建一条直线水平线,希望它有所帮助!。

回答by Muhammad Aamir Ali

You can make a drawable like circle, line, rectangle etc through shapes in xml as follow:

您可以通过 xml 中的形状制作圆形、线条、矩形等可绘制对象,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="line" >

    <solid android:color="#00000000" />

    <stroke
        android:width="2dp"
        android:color="#808080" />

</shape>

回答by user4757345

this code adds horizontal line to a linear layout

此代码将水平线添加到线性布局

View view = new View(this);
LinearLayout.LayoutParams lpView = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1); // --> horizontal
view.setLayoutParams(lpView);
view.setBackgroundColor(Color.DKGRAY);

linearLayout.addView(view);