android - 自定义 View 转换为位图返回黑色图像

标签 android bitmap

我需要创建一个自定义 View ,然后将其保存到 png 文件到 sdcard 中。现在我在 SD 卡中收到黑色图像。我无法在代码中找出问题所在。谁能帮帮我。

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:orientation="vertical" >
        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/black" />

        <TextView
            android:id="@+id/address"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/black" />
</LinearLyout>

在我的 java 文件中,我膨胀了线性布局并将数据设置为 TextView ,然后调用:

private Bitmap convertViewToBitmap(LinearLayout layout) {
    layout.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
    int width = layout.getMeasuredWidth();
    int height = layout.getMeasuredHeight();

    //Create the bitmap
    Bitmap bitmap = Bitmap.createBitmap(width, 
            height, 
            Bitmap.Config.ARGB_8888);
    //Create a canvas with the specified bitmap to draw into
    Canvas c = new Canvas(bitmap);

    //Render this view (and all of its children) to the given Canvas
    view.draw(c);
    return bitmap;
}

获取位图后,我将其保存到 sdcard 中,如下所示:

private void saveBitmapTpSdCard(Bitmap bitmap, String fileName) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 40, bytes);

        File f = new File(Environment.getExternalStorageDirectory()
                + File.separator + getString(R.string.app_name));

        try {
            if(!f.exists()) {
                f.mkdirs();
            }
            File imageFile = new File(f, fileName + ".png");
            FileOutputStream fo = new FileOutputStream(imageFile);
            fo.write(bytes.toByteArray());
            fo.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
}

最佳答案

我通过添加这一行让它工作:

view.layout(0, 0, width, height);

在使用 Bitmap.createBitmap 创建位图之前

关于android - 自定义 View 转换为位图返回黑色图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23535675/

相关文章:

java - 包含库项目时出现 ClassNotFoundException(Eclipse、Android)

java - Android加载图片到ListView AsyncTask

android drawable to bitmap引起的OOM

java - 如何将图像转换为位图形式的 java 应用程序到 android 设备

java - Android NDK ndk-build helloJni错误

android - 如果 Smartface.io 中的网络连接丢失,我该如何停止所有进程

android - 将导航选项卡与 ActionBarSherlock 一起使用时不显示 fragment

android - FFMPEG + Android 包装器使用 FFMPEG 的最新版本

java - 在 Android 中调整图像大小

java - 如何正确设置用户选择的文件夹中图像的 Uri 以在 ImageView 中显示?