I have two Views (Textview
& ImageView
) in the FrameLayout
, I want to save the image with text. For this, I covert the View to a bitmap.
My xml is:
<FrameLayout
android:id="@+id/framelayout"
android:layout_marginTop="30dip"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
<ImageView
android:id="@+id/ImageView01"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
<TextView android:id="@+id/text_view"
android:layout_marginTop="30dip"
android:layout_width="wrap_content"
android:maxLines="20"
android:scrollbars="vert开发者_开发百科ical"
android:layout_height="wrap_content"/>
</FrameLayout>
How to convert View into Bitmap
FrameLayout view = (FrameLayout)findViewById(R.id.framelayout);
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bm = view.getDrawingCache();
I used to use the buildDrawingCache()
method to get a bitmap of my layout, but I was having trouble with it when the view was large. Now I use the following method:
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);
Hi you can get a bitmap of a view using the following snippet
mView.setDrawingCacheEnabled(true);
mView.getDrawingCache();
why don't you write your class that extends ImageView and override method onDraw and put there your image and text, it's more easy
First Of all, you need to add dependency
implementation 'com.github.vipulasri.layouttoimage:library:1.0.0'
Then Convert Layout to Bitmap
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());
}
});
Here I have added a post Runnable thread which ensure the createBitmap method will execute only after v.buildDrawingCache(true);. v.buildDrawingCache(true); takes few milisec time in some mobile and that is the reason it crash in some mobile. Please try this solution if you face null pointer exception for Bitmap object.
精彩评论