简体   繁体   English

在View Android上动态绘制线条

[英]Dynamically draw lines on View Android

I want to implement something like below: 我想实现类似以下的内容:

情节

The default would be one red dot + 1 plot on the x-axis. 默认值为x轴上一个红点+ 1个图。 User can then add up to 5 red dots and the view will be redrawn and show the number of dots and respective plots with it distance shown below the plot. 然后,用户最多可以添加5个红点,然后将重新绘制视图,并显示点数和各个图,其距离显示在图下方。 Does any one knows how can I achieve this? 有谁知道我怎么能做到这一点? How can I draw the lines (plot) on the view? 如何在视图上绘制线(图)?

Any help is much appreciated!! 任何帮助深表感谢!! Thanks... 谢谢...

you can create a subclass of View class and override its onDraw() method 您可以创建View类的子类并覆盖其onDraw()方法

Then you can draw lines, text and circles (dots) on the canvas to show such image inside the View 然后,您可以在画布上绘制线条,文本和圆圈(点)以在“视图”中显示此类图像

Activity: 活动:

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

And the view: 和视图:

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM