2011-06-16 57 views
3

我想用觸摸監聽器在屏幕上繪製一條線,但是當我嘗試再次畫線時,它會擦除​​上一行。我正在使用此代碼: -畫線 - Android

我無法找到問題的解決方案。

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(); 
    } 
} 
+0

發佈多次http://stackoverflow.com/questions/6372556/android-draw-line – Matthieu 2011-06-16 13:45:50

回答

2

我敢肯定,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(); 
    } 
} 
+0

@ Lawngnomehitman-如何做到這一點??? – sanchit 2011-06-16 13:54:09

+0

我更新了我的答案,以包含顯示基本想法的示例代碼 – Travis 2011-06-17 11:10:55