为什么绘制到 Android canvas 没有修改我的位图?

Why is drawing to the Android canvas not modifying my bitmap?

正在寻求帮助来解决此绘图未修改位图的原因。看了很多例子,我的代码似乎与列出的相符。我错过了什么?

这是相关代码(class 在别处构造,drawSomething() 调用在 onTouchEvent 处理程序中)。为了简洁起见,我缩短了代码:

class MyView extends View {

    Bitmap mBitmap;
    BitmapDrawable mBitmapDrawable;
    Canvas mCanvas;
    Paint mPaint;

    public MyView(Context context) {
        super(context);
        mBitmap = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
        mBitmapDrawable = new BitmapDrawable(getResources(), mBitmap);
        mCanvas = new Canvas(mBitmap);
        mCanvas.setBitmap(mBitmap);
        mPaint = new Paint();
        mPaint.setColor(Color.parseColor("#00FF00"));
        mPaint.setStrokeWidth(10);
    }

    public void drawSomething() {
        mCanvas.drawColor(0xFF00FF00);  // This should "fill" the canvas
        int radius = 10;
        mCanvas.drawCircle(50, 50, radius, mPaint);     // This should draw a circle at (50, 50)

        int count=0;
        for (int i=0; i<mBitmap.getWidth(); i++)
        {
            for (int j=0; j<mBitmap.getHeight(); j++)
            {
                if (mBitmap.getPixel(i, j) > 0)
                {
                    count += 1;
                }
            }
        }
        if (count == 0)
        {
            Log.v("MyApp", "Nothing was drawn!");
        }
    }
}

找出问题所在。事实证明 canvas 绘图按预期工作(这并不奇怪)。还有另外两个问题。

我忽略了 Java int 数据类型的符号性。 int0xFF00FF00 的计算结果小于 0。这解释了为什么我的故障排除代码中的计数计算结果为 0。

我没有在位图中看到任何绘图,因为我最终使用 mBitmapDrawable 对象的 draw 方法将位图绘制到屏幕上。更改我的代码以使用 Canvas 对象的 drawBitmap 方法后,可变位图被正确绘制。我推测 BitmapDrawable 在其构造函数中复制了提供的位图,因此我没有看到我对位图所做的修改。