android - 如何在图像上绘画并将该图像保存到 Android?

标签 android android-layout canvas android-emulator android-widget

我是 Canvas 新手。我想使用我已经保存的图像并想在该图像上进行一些绘画。之后我想保存它。

我知道使用 Canvas 是可能的。我可以在图像上绘画,但是当我要存储该图像时,它只保存了绘画。不是有绘画的图像。

那么有没有 friend 可以告诉我如何在图像上绘画并保存该图像的代码?

谢谢。

这是我用来在 SurfaceView 上绘制的代码。 源代码:

    @Override
        public void run() {
            //Canvas canvas = null;
            while (_run){

                try{
                    canvas = mSurfaceHolder.lockCanvas(null);
                    if(mBitmap == null){
                        mBitmap =  Bitmap.createBitmap (1, 1, Bitmap.Config.ARGB_8888);
                    }

                    final Canvas c = new Canvas (mBitmap);
                    //canvas.drawColor(0, PorterDuff.Mode.CLEAR);
                    c.drawColor(0, PorterDuff.Mode.CLEAR);
                    canvas.drawColor(Color.WHITE); 
//                  Bitmap kangoo = BitmapFactory.decodeResource(getResources(),R.drawable.icon);

//                    if(!(DrawingActivity.imagePath==null)){
//                      canvas.drawBitmap(DrawingActivity.mBitmap, 0, 0, null);
//                    }
                    commandManager.executeAll(c);
                    canvas.drawBitmap (mBitmap, 0,  0,null);
                } finally {

                    mSurfaceHolder.unlockCanvasAndPost(canvas);
                }
            }

        }

我正在使用 mBitmap 将位图保存到 SDCard。

最佳答案

你的问题是你在整个 Canvas 上一遍又一遍地画画:

 final Canvas c = new Canvas (mBitmap); // creates a new canvas with your image is painted background
 c.drawColor(0, PorterDuff.Mode.CLEAR); // this makes your whole Canvas transparent
 canvas.drawColor(Color.WHITE);  // this makes it all white on another canvas
 canvas.drawBitmap (mBitmap, 0,  0,null); // this draws your bitmap on another canvas

大致这样使用逻辑:

@Override
public void run() {

Canvas c = new Canvas(mBitmap);


/* Paint your things here, example: c.drawLine()... Beware c.drawColor will fill your canvas, so your bitmap will be cleared!!!*/
...

/* Now mBitmap will have both the original image & your painting */
String path = Environment.getExternalStorageDirectory().toString(); // this is the sd card
OutputStream fOut = null;
File file = new File(path, "MyImage.jpg");
fOut = new FileOutputStream(file);
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
}

另外不要忘记添加必要的权限以保存您的文件:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

外面<application></application>在您的 list 文件中。

关于android - 如何在图像上绘画并将该图像保存到 Android?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8047914/

相关文章:

Android:最近的应用程序似乎有谷歌提供的广告,是否有一些新的 API?

Android 应用程序在尝试启动新 Activity 时崩溃

java - 将字节数组转换为字符串时截断 JSON

android - 如何在App上显示一次启动画面?

javascript - 将 Canvas 分成几 block

javascript - JS Canvas 在各个方向上调整大小

android - registerReceiver 中需要表达式 - Android Studio

Android Button背景颜色在xml上没有改变

android - 所选链接背景颜色的 Android Style 属性是什么?

javascript - 一旦实例化/绘制到 Canvas ,移除/删除函数对象的最佳方法是什么?