2014-10-03 83 views
1

我有一個自定義繪製視圖,我根據點擊和移動座標繪製線條。 這個自定義視圖被添加到我的主要acitvity中,在那裏我可以更改自定義視圖中的繪畫對象的筆觸寬度。我將當前筆觸寬度存儲在靜態類中。在onDraw()方法中,我想用舊筆畫寬度重新繪製舊Pathes,我可以用不同的寬度繪製它,但始終是當前設置的筆觸寬度。Android:使用不同筆觸寬度繪製

MainActivity:

@Override 
public void onItemSelected(AdapterView<?> parent, View view, int position, 
     long id) { 
    if (position == 0) { 
     Memory.setStrokeWidth(10); //Set stroke width in static class 
    } 
    if (position == 1) { 
     Memory.setStrokeWidth(25); 
    } 
    if (position == 2) { 
     Memory.setStrokeWidth(40); 
    } 


} 

自定義繪製查看:

private Paint paint; 
private Path path; 
private HashMap<Path, Float> strokeWidthMemory; 

@Override 
protected void onDraw(Canvas canvas) { 

    paint.setStrokeWidth(Memory.getStrokeWidth()); 
    canvas.drawPath(path, paint);       
    strokeWidthMemory.put(path, paint.getStrokeWidth()); //Save drawn path with stroke width in HashMap 

    //Redraw old lines with stored stroke width 
    for (Path p : strokeWidthMemory.keySet()) { 
     paint.setStrokeWidth(strokeWidthMemory.get(p)); 
     canvas.drawPath(p, paint); 
    } 

} 

@Override 
public boolean onTouchEvent(MotionEvent event) { 
    // Get the coordinates of the touch event. 
    float eventX = event.getX(); 
    float eventY = event.getY(); 

    switch (event.getAction()) { 
    case MotionEvent.ACTION_DOWN: 
     // Set a new starting point 
     path.moveTo(eventX, eventY); 

     return true; 
    case MotionEvent.ACTION_MOVE: 
     // Connect the points 
     path.lineTo(eventX, eventY); 
     break; 
    default: 
     return false; 
    } 

    // Makes our view repaint and call onDraw 
    invalidate(); 

    return true; 
} 

回答

1

附加筆劃寬度ACTION_MOVE當你描繪軌跡。如果您在onDraw有不是每次添加描邊寬度調用無效哈希映射與當前筆劃寬度值

private Paint paint; 
    private Path path; 
    private HashMap<Path, Float> strokeWidthMemory; 

    @Override 
    protected void onDraw(Canvas canvas) { 

     paint.setStrokeWidth(Memory.getStrokeWidth()); 
     canvas.drawPath(path, paint);       


     //Redraw old lines with stored stroke width 
     for (Path p : strokeWidthMemory.keySet()) { 
      paint.setStrokeWidth(strokeWidthMemory.get(p)); 
      canvas.drawPath(p, paint); 
     } 

    } 

    @Override 
    public boolean onTouchEvent(MotionEvent event) { 
     // Get the coordinates of the touch event. 
     float eventX = event.getX(); 
     float eventY = event.getY(); 

     switch (event.getAction()) { 
     case MotionEvent.ACTION_DOWN: 
      // Set a new starting point 
      path.moveTo(eventX, eventY); 

      return true; 
     case MotionEvent.ACTION_MOVE: 
      // Connect the points 
      path.lineTo(eventX, eventY); 
      strokeWidthMemory.put(path, paint.getStrokeWidth()); //Save drawn path with stroke width in HashMap 
      break; 
     default: 
      return false; 
     } 

     // Makes our view repaint and call onDraw 
     invalidate(); 

     return true; 
    } 

更新看一看this answer以供參考。