截取表面视图的截图在android中不起作用

时间:2014-12-09 10:05:49

标签: android android-canvas surfaceview surface

在我的Android应用程序中,我有表面视图,我有画布,用户可以在画布上绘制。现在我想捕获画布图像并将其存储到SD卡。 以下是我的代码 -

 Bitmap bitmap = Bitmap.createBitmap(maxX, maxY, Bitmap.Config.RGB_565);
 canvas.setBitmap(bitmap);
 String mFile = path+"/drawing.png";
        Bitmap bitmap = drawBitmap();
        File file = new File(mFile);
        FileOutputStream fos = new FileOutputStream(file);
        bitmap.compress(CompressFormat.PNG, 100, fos);
        fos.flush();
        fos.close();

代码运行但是当我在图像路径文件上打开sd卡时会创建名称,但是当打开图像时它是黑色的。 如何从android中的canvas中捕获图像。

1 个答案:

答案 0 :(得分:-1)

只需传递要存储快照的表面视图对象和文件路径。它工作得很好。

public static void takeScreenshot(View view, String filePath) {
            Bitmap bitmap = getBitmapScreenshot(view);

            File imageFile = new File(filePath);
            imageFile.getParentFile().mkdirs();
            try {
                OutputStream fout = new FileOutputStream(imageFile);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
                fout.flush();
                fout.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

public static Bitmap getBitmapScreenshot(View view) {
        view.measure(MeasureSpec.makeMeasureSpec(view.getWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(view.getHeight(), MeasureSpec.EXACTLY));
        view.layout((int)view.getX(), (int)view.getY(), (int)view.getX() + view.getMeasuredWidth(), (int)view.getY() + view.getMeasuredHeight());

        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache(true);
        Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
        view.setDrawingCacheEnabled(false);

        return bitmap;
    }