画线-Android

发布于 2024-11-15 21:18:25 字数 394 浏览 3 评论 0原文

我想使用触摸监听器在屏幕上画一条线,但是当我尝试再次画线时,它会删除前一行。我正在使用这段代码:-

我无法找到问题的解决方案。

public class Drawer extends View
{
    public Drawer(Context context)
    {
        super(context);
    }

    protected void onDraw(Canvas canvas)
    {
        Paint p = new Paint();
        p.setColor(colordraw);
        canvas.drawLine(x1, y1, x2, y2, p);
        invalidate();
    }
}

I want to draw a line on screen using touch listener, but when i try to draw line again it erases the previous line. I am using this code:-

I am unable to find a solution to the problem.

public class Drawer extends View
{
    public Drawer(Context context)
    {
        super(context);
    }

    protected void onDraw(Canvas canvas)
    {
        Paint p = new Paint();
        p.setColor(colordraw);
        canvas.drawLine(x1, y1, x2, y2, p);
        invalidate();
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

年华零落成诗 2024-11-22 21:18:25

我很确定 invalidate() 会擦除画布,因此您必须保留要绘制的线条的集合。然后你需要在调用 invalidate() 之前每次都绘制它们。

private class Line {

    public Line(int x1, int y1, int x2, int y2) {
        this.x1 = x1;
        this.y1 = y1;
        this.x2 = x2;
        this.y2 = y2;
    }
    ...    
}

public class Drawer extends View
{  
    ArrayList<Line> lines;
    public Drawer(Context context)
    {
        super(context);
        lines = new ArrayList<Line>();
    }

    public void addLine(int x1, int y1, int x2, int y2) {
        Line newLine = new Line(x1, y1, x2, y2);
        lines.add(newLine);
    }

    protected void onDraw(Canvas canvas)
    {
        Paint p = new Paint();
        p.setColor(colordraw);
        for (Line myLine : lines) {
            canvas.drawLine(myLine.getX1(), myLine.getY1(), myLine.getX2(), myLine.getY2(), p);
        }
        invalidate();
    }
}

I'm pretty sure that invalidate() wipes the canvas, so you have to keep a collection of lines that you want to draw. Then you need to draw ALL of them EVERY time before calling invalidate().

private class Line {

    public Line(int x1, int y1, int x2, int y2) {
        this.x1 = x1;
        this.y1 = y1;
        this.x2 = x2;
        this.y2 = y2;
    }
    ...    
}

public class Drawer extends View
{  
    ArrayList<Line> lines;
    public Drawer(Context context)
    {
        super(context);
        lines = new ArrayList<Line>();
    }

    public void addLine(int x1, int y1, int x2, int y2) {
        Line newLine = new Line(x1, y1, x2, y2);
        lines.add(newLine);
    }

    protected void onDraw(Canvas canvas)
    {
        Paint p = new Paint();
        p.setColor(colordraw);
        for (Line myLine : lines) {
            canvas.drawLine(myLine.getX1(), myLine.getY1(), myLine.getX2(), myLine.getY2(), p);
        }
        invalidate();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文