2013-05-13 139 views
1

所以我在繪圖應用中面臨這個奇怪的問題。Android在另一條路徑上繪製一條路徑的頂部

我從上到下和從左到右畫出了從1到8的這些行。

enter image description here

雖然我畫的線,它顯示爲它繪製所有其他敵後。每當我放開屏幕,它就會彈出一個有時,這似乎是完全隨機的。

我在任何時候都可以俯視一切來繪製其他任何東西?

我DrawView.java:

public class DrawView extends View implements OnTouchListener { 

    private Path path = new Path(); 
    private Paint paint = new Paint(); 

    private Map<Path, Paint> pathMap = new HashMap<Path, Paint>(); 

    private boolean isScreenCleared = false; 

    public DrawView(Context context) { 
     super(context); 
     this.setOnTouchListener(this); 

     paint.setColor(Color.BLACK); 
     paint.setAntiAlias(true); 
     paint.setStrokeWidth(5); 
     paint.setStyle(Paint.Style.STROKE); 
     paint.setStrokeJoin(Paint.Join.ROUND); 
     paint.setStrokeCap(Paint.Cap.ROUND); 

    } 

    @Override 
    public void onDraw(Canvas canvas) { 
     if (isScreenCleared) { 
      pathMap.clear(); 
      canvas.drawColor(Color.WHITE); 
      isScreenCleared = false; 
     } else { 
      //Current line 
      canvas.drawPath(path, paint); 

      //All other lines 
      for (Map.Entry<Path, Paint> p : pathMap.entrySet()) { 
       canvas.drawPath(p.getKey(), p.getValue()); 
      } 
     } 
    } 

    public boolean onTouch(View view, MotionEvent event) { 
     float eventX = event.getX(); 
     float eventY = event.getY(); 

     switch (event.getAction()) { 
     case MotionEvent.ACTION_DOWN: 
      path = new Path(); 
      path.reset(); 
      path.moveTo(eventX, eventY); 
      return true; 
     case MotionEvent.ACTION_MOVE: 
      path.lineTo(eventX, eventY); 
      break; 
     case MotionEvent.ACTION_UP: 
      Paint newPaint = new Paint(); 
      newPaint.set(paint); 
      pathMap.put(path, newPaint); 
      break; 
     default: 
      return false; 
     } 

     invalidate(); 
     return true; 
    } 

    public float getRadius() { 
     return paint.getStrokeWidth(); 
    } 

    public void setRadius(float radius) { 
     paint.setStrokeWidth(radius); 
    } 

    public void setColor(int color) { 
     paint.setColor(color); 
     System.out.println("Color set to: " + color); 
    } 

    public void clearScreen() { 
     isScreenCleared = true; 
     invalidate(); 
    } 
} 

我實例drawView函數在我的MainActivity這樣的:

Relative layout = (RelativeLayout) findViewById(R.id.drawscreen); 

DrawView dv = new DrawView(layout.getContext()); 

回答

0

好吧,我發現由於Spartygw問題,但發現的東西比Vector好多了。

有確定性的LinkedHashMap

因此,使用它可以解決問題。

另外:

它畫的一切落後而圖紙是在我結束一個快速的錯誤,因爲我顯然需要整個(投資相連)的HashMap後得出當前行

+0

除非你正在做的事情,你還沒有顯示,使用LinkedHashMap不是最好的容器選擇。這是一個比Vector或List更重的容器或... – spartygw 2013-05-14 13:25:01

0

不要使用HashMap來存儲路徑。使用一個Vector並添加新的路徑到最後。然後,當你繪製它們並遍歷你的矢量時,你將按照正確的順序繪製它們,並且將它們放在最前面。

從HashMap的文檔:

Note that the iteration order for HashMap is non-deterministic. 
+0

感謝您發現問題!我發佈了使用LinkedHashMap而不是Vector的答案。 – James 2013-05-13 20:49:56

+0

我能從中得到一個可接受的答案嗎?我需要點數! :) – spartygw 2013-05-13 21:00:32

+0

再次強硬... – spartygw 2013-05-14 13:26:35