Android Paint PorterDuff.Mode.CLEAR

And*_*oid 8 android bitmap android-canvas

我正在使用类似于Android SDK的Finger Paint演示的Canvas应用程序.我的问题是我正在使用的时候PorterDuff.Mode.CLEAR.当绘制和画布时,如果我试图擦除某些东西,它工作正常.但是如果我试图将我的图像保存为PNG文件,则橡皮擦的笔划会变成黑色,我不确定为什么会发生这种情况.这是我正在做的一个例子:

@Override
    protected void onDraw(Canvas canvas) {
        canvas.drawColor(Color.WHITE);
        canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);

        canvas.drawPath(mPath, mPaint);
    }
Run Code Online (Sandbox Code Playgroud)

橡皮擦:

case ERASE_MENU_ID:
            mPaint.setXfermode(new PorterDuffXfermode(
                                                    PorterDuff.Mode.CLEAR));
            return true;
Run Code Online (Sandbox Code Playgroud)

以及我如何保存图像:

            Calendar currentDate = Calendar.getInstance();
            SimpleDateFormat formatter= new SimpleDateFormat("yyyyMMMddHmmss");
            String dateNow = formatter.format(currentDate.getTime());
            File dir = new File(mImagePath);
            if(!dir.exists())
                dir.mkdirs();

            File file = new File(mImagePath + "/" + dateNow +".png");

            FileOutputStream fos;
            try {
                fos = new FileOutputStream(file);
                mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.close();
                Toast.makeText(getApplicationContext(), "File saved at \n"+mImagePath + "/" + dateNow +".png", Toast.LENGTH_LONG).show();
            } catch (FileNotFoundException e) {
                Log.e("Panel", "FileNotFoundException", e);
            } 
            catch (IOException e) {
                Log.e("Panel", "IOEception", e);
            }
            return true;
Run Code Online (Sandbox Code Playgroud)

这是一个图像的例子:

这是我的画布在保存之前的样子:

在此输入图像描述

这是将其保存在SD卡上后的图像:

在此输入图像描述

Ren*_*ard 12

指纹代码的问题在于,您看到的内容与压缩到png中的内容不同.看看onDraw().首先,您将屏幕绘制为白色.然后添加位图.因为你使用了Porter Duff Clear,所以位图的擦除部分包含实际上透明的黑色像素(值0x00000000).但因为你有白色背景,这些黑色像素显示为白色.

要解决此问题,请更改保存代码以执行与绘制代码相同的操作

 try {
                    fos = new FileOutputStream(file);
                    Bitmap saveBitmap = Bitmap.createBitmap(mBitmap);
                    Canvas c = new Canvas(saveBitmap);
                    c.drawColor(0xFFFFFFFF);
                    c.drawBitmap(mBitmap,0,0,null);
                    saveBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                    saveBitmap.recycle();
...
Run Code Online (Sandbox Code Playgroud)

或者不要使用PortDuff.Clear:

    case ERASE_MENU_ID:
        mPaint.setColor(Color.WHITE);
Run Code Online (Sandbox Code Playgroud)