在退出活动时,位图/画布会被缓存

时间:2013-11-06 14:56:58

标签: android canvas bitmap

我正在WebView上创建一个画布(如下所示)。我正在实现撤消功能,因此用户可以通过单击按钮删除绘制的路径。但是,即使我离开活动并返回,画布也总是填充我的路径。删除它的唯一方法是关闭应用程序。如何删除或重新创建位图canvasBitmap或画布drawCanvas

public static Canvas drawCanvas;
public static Bitmap canvasBitmap;
Rect clipBounds;

public static ArrayList<Path> paths = new ArrayList<Path>();
public static ArrayList<Paint> colors = new ArrayList<Paint>();

// Creates bitmap for canvas
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    drawCanvas = new Canvas(canvasBitmap);
}

// Saves the paths onto the bitmap and adjust scale based on current zoom level
@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    clipBounds = canvas.getClipBounds();
    drawPaint.setStrokeWidth(8/mScaleFactor);
    canvas.scale(mScaleFactor, mScaleFactor, 0, 0);

    for (int i = 0; i < colors.size(); i++) {
        canvas.drawPath(paths.get(i), colors.get(i));
    }
    canvas.drawPath(drawPath, drawPaint);
    canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
    invalidate();
}

public boolean onTouchEvent(MotionEvent event) {
    pointerCount = event.getPointerCount();
    mScaleDetector.onTouchEvent(event);
    float touchX = (event.getX() + clipBounds.left) / mScaleFactor;
    float touchY = (event.getY() + clipBounds.top) / mScaleFactor;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                drawPath.moveTo(touchX, touchY);
                break;
            case MotionEvent.ACTION_MOVE:
                drawPath.lineTo(touchX, touchY);
                break;
            case MotionEvent.ACTION_UP:
                 Paint newPaint = new Paint();
                newPaint.set(drawPaint); //copies the values over from the current class's paint
                colors.add(newPaint);
                paths.add(drawPath);
                drawPath = new Path();
                drawPath.reset();
                break;
            default:
                return false;
        }
    }
    invalidate();
    return true;
}

public void reDrawUndo () {
     if (paths.size() > 0) {
         paths.remove(paths.size() - 1);
         colors.remove(colors.size() - 1);
         invalidate();
     }
}

我用这种方法在画布上绘制带有相应颜色的路径:

for (int j = 0; j < paths.size(); j++) {
    drawCanvas.drawPath(paths.get(j),colors.get(j));
           }

1 个答案:

答案 0 :(得分:0)

您在列表“路径”上保留所有积分并保持当前绘制的路径“drawPath”:这是您的“逻辑”。

当你想在屏幕上看到它们时,你可以在提供的画布上用onDraw(Canvas canvas)方法绘制它们:这是你在UI上绘制的逻辑。

当你想保存积分时,你可以选择很少的选项取决于你想要达到的目标。当你想要在其上绘制路径时保存位图 - 你创建一个新的位图(你不必一直将它保存在内存中)和一个画布,你可以在新画布上绘制所有点。如果要保存点以便以后可以将它们保存为文件或数据库中的整数或文本。