I try to create a View programaticaly by inflating an layout.
View marker = ((LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.overlay_view, null);
Now i want to convert this View to a Bitmap:
public static Bitmap createDrawableFromView(Context context, View view){
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
Bitmap cache = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(cache);
view.draw(canvas);
return cache;
}
I also tried measure(1, 1) and layout(0 ,0 ,0 ,0) without any changes.
The Bitmap looks like the filled layout.
Now the Problem: If i put something into the View thats makes the View bigger than the Displaysize in width or height (example: a TextView with a long text), the Bitmap is also bigger.
The Views XML width and height is WRAP_CONTENT but it didnt works.
I never put this View somewhere to display it (becouse i only need the Bitmap).
Question: How can i WRAP the View to a maximum of width = displayWidth?
I tried view.setLayoutParams(new LayoutParam(100, 100)) but it was also bigger than 100?! I really dont understand whats happened, when i inflate the layout and set the content of the View.
The view.getMeasuredWidth and Height is always bigger as my display?! (if i put something bigger in it)
Here is an Example of the Layout:
<RelativeLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/somedrawable"
android:padding="10dp"
android:clickable="true">
<TextView android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"/>
<TextView android:id="@+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:text="Description"
android:textSize="20dp"
android:textColor="#ffffff"/>
</RelativeLayout>
I found a solution:
first step: add new LayoutParams to the view. This is important, becouse without you will get a NullPointer.
Second:
for
view.measure()i usedMeasureSpec.makeMeasureSpec(displayMetrics.heightPixels, MeasureSpec.AT_MOST));. First parameter is the display width or heigt and the second is the mode AT_MOST, this is needed to “wrap” the View.Works great! (for me :p )