在画布上绘制而不清除先前绘制的位图

Cod*_*ode 5 android android-canvas

我需要在画布上绘制位图,然后开始在其上绘制。当我在画布上绘制其他对象时,先前绘制的位图将被清除。为了避免位图被清除,我必须在每次 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());
    }

}
Run Code Online (Sandbox Code Playgroud)

那么,什么是最有效的方法来绘制以前绘制的图形而不丢失它。

小智 0

我发现不使用自定义视图类和 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();
}
Run Code Online (Sandbox Code Playgroud)