如何将View转换为Bitmap
FrameLayout view = (FrameLayout)findViewById(R.id.framelayout);
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bm = view.getDrawingCache();
我曾经使用
buildDrawingCache()
方法来获取布局的位图,但是 当视图很大时,我遇到了麻烦。现在我使用以下方法:
FrameLayout view = findViewById(R.id.framelayout);
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
您好,您可以使用以下代码片段获取视图的位图
mView.setDrawingCacheEnabled(true);
mView.getDrawingCache();
为什么你不编写扩展 ImageView 的类并重写 onDraw 方法并将图像和文本放在那里,这样更容易
首先需要添加依赖
implementation 'com.github.vipulasri.layouttoimage:library:1.0.0'
然后将布局转换为位图
RelativeLayout pdfmain;
Layout_to_Image layout_to_image;
Bitmap mBitmap;
layout_to_image = new Layout_to_Image(AllotmentDoc.this, pdfmain);
mBitmap = layout_to_image.convert_layout();
FrameLayout v = (FrameLayout)findViewById(R.id.frme1);
v.setDrawingCacheEnabled(true);
// this is the important code :)
// Without it the view will have a dimension of 0,0 and the bitmap will be null
v.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
v.buildDrawingCache(true);
v.post(new Runnable() {
@Override
public void run() {
// Bitmap b = v.getDrawingCache();
Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false); // clear drawing cache
Log.e("ss","ss"+b.getHeight());
}
});
这里我添加了一个后置可运行线程,确保 createBitmap 方法仅在 v.buildDrawingCache(true); 之后执行。 v.buildDrawingCache(true);在某些手机上需要几毫秒的时间,这就是它在某些手机上崩溃的原因。如果您遇到 Bitmap 对象的空指针异常,请尝试此解决方案。
公共静态位图loadBitmapFromView(视图视图){ view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
final Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}