在View Android上动态绘制线条

时间:2014-12-16 01:25:55

标签: android view graph plot line

我想实现类似下面的内容:

Plot

默认为x轴上的一个红点+1图。然后,用户可以添加最多5个红点,并且将重新绘制视图,并显示点的数量和相应的图,其中距离显示在图下方。有谁知道我怎么能做到这一点?如何在视图上绘制线条(绘图)?

非常感谢任何帮助!!谢谢......

1 个答案:

答案 0 :(得分:0)

您可以创建View类的子类并覆盖其onDraw()方法

然后,您可以在画布上绘制线条,文本和圆圈(点),以在视图中显示此类图像

的活动:

package hk.patsolution.drawlineexample.app;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        addContentView(new MyView(this), new ViewGroup.LayoutParams(1000,1000));
    }
}

观点:

package hk.patsolution.drawlineexample.app;

/**
 * Created by patrickchan on 16/12/14.
 */

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

public class MyView extends View {
    private Paint paint;
    private Paint black;

    public MyView(Context c){
        this(c,null);
    }

    public MyView(Context c, AttributeSet s) {
        super(c, s);
        paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStrokeWidth(10);

        black=new Paint();
        black.setColor(Color.BLACK);
        paint.setStrokeWidth(10);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.drawLine(0, 100, 1000, 100, black);
        canvas.drawLine(100, 0, 100, 1000, black);

        canvas.drawText("hello", 200, 200, paint);

        canvas.drawCircle(400, 400, 100, paint);
    }

}