我需要创建一个自定义视图,然后将其保存为 png 文件到 SD 卡中。现在我在 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 文件中,我膨胀了线性布局并将数据设置为文本视图,然后我调用:
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;
}
获取位图后,我将其保存到 SD 卡,如下所示:
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 创建位图之前
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)