2015-02-06 71 views
1

我需要在畫布上繪製位圖,然後開始繪製它。當我在畫布上繪製其他對象時,先前繪製的位圖被清除。爲了避免位圖被清除,我必須在每次ondraw()調用中繪製它。必須有其他方法來更新先前繪製的圖形,否則它會非常高效,因爲我可能需要繪製許多位圖。在畫布上繪製而不使以前繪製的位圖清除

@Override 
protected void onDraw(Canvas mCanvas) { 
    for (Pair<Path, Paint> p : paths) { 
     mCanvas.drawPath(p.first, p.second); 
    } 
    if(merge){ 
     canvas.drawBitmap(bmp, transform, new Paint()); 
    } 

} 

那麼,什麼是最有效的方式來繪製先前繪製的繪圖而不會丟失它。

回答

1

我發現不使用自定義視圖類和onDraw方法,使畫布不清楚,因此我不得不手動清除它我自己的目的。

請參閱下面的代碼,只是刪除canvas.drawColor線,因爲這是我畫的畫布再次清晰。

public void doCanvas(){ 
    //Create our resources 
    Bitmap bitmap = Bitmap.createBitmap(mLittleChef.getWidth(), mLittleChef.getHeight(), Bitmap.Config.ARGB_8888); 
    final Canvas canvas = new Canvas(bitmap); 
    final Bitmap chefBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.dish_special); 
    final Bitmap starBitmap= BitmapFactory.decodeResource(getResources(),R.drawable.star); 

    //Link the canvas to our ImageView 
    mLittleChef.setImageBitmap(bitmap); 

    ValueAnimator animation= ValueAnimator.ofInt(canvas.getWidth(),0,canvas.getWidth()); 
    animation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { 
     @Override 
     public void onAnimationUpdate(ValueAnimator animation) { 
      int value = (Integer) animation.getAnimatedValue(); 
      //Clear the canvas 
      canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); 
      canvas.drawBitmap(chefBitmap, 0, 0, null); 
      canvas.save(); 
      canvas.translate(value,0); 
      canvas.drawBitmap(starBitmap, 0, 0, null); 
      canvas.restore(); 
      //Need to manually call invalidate to redraw the view 
      mLittleChef.invalidate(); 
     } 
    }); 
    animation.addListener(new AnimatorListenerAdapter(){ 
     @Override 
     public void onAnimationEnd(Animator animation) { 
      simpleLock= false; 
     } 
    }); 
    animation.setInterpolator(new LinearInterpolator()); 
    animation.setDuration(mShortAnimationDuration); 
    animation.start(); 
}