rendering a TextView in a Bitmap for an android widget
Posted
by
foke
on Stack Overflow
See other posts from Stack Overflow
or by foke
Published on 2011-01-02T16:43:40Z
Indexed on
2011/01/02
16:54 UTC
Read the original article
Hit count: 190
android
|android-widget
I'm building a widget which displays some text. By widget I mean the kind which lies on the desktop.
The problem is that I want to change text's font at runtime. There is several textview I would like, at runtime, to set the first as bold, the second blue and italic for example, etc.
I came up with this :
TextView tv = new TextView(context); tv.setText(stringToDisplay); tv.setTextColor(0xa00050ff); // example tv.setTextSize(30); // example
Bitmap b = loadBitmapFromView(tv); updateViews.setImageViewBitmap(R.id.id_of_the_imageview, b);
with
private static Bitmap loadBitmapFromView(View v) { Bitmap b = Bitmap.createBitmap(v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(b); v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height); v.draw(c); return b; }
but it wont work (NullPointerException on first line of loadBitmap), until I replace v.getLayoutParams().width, v.getLayoutParams().height
by fixed sizes like 250, 50
Bitmap b = Bitmap.createBitmap(250, 50, Bitmap.Config.ARGB_8888);
// ...
v.layout(0, 0, 250, 50);
But that's not a good solution ...
so I tried this :
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View row = li.inflate(R.layout.widget_text, null);
TextView tv = (TextView) row.findViewById(R.id.id_of_the_textview);
widget_text
being a layout similar to the displayed one but with TextViews instead of ImageViews, in the hope to get some size information out of it ..
but it's not working and I get this exception :
01-02 17:35:06.001: ERROR/AndroidRuntime(11025): Caused by: java.lang.IllegalArgumentException: width and height must be > 0
on the call to Bitmap.createBitmap()
so, someone could point me in the right direction?
© Stack Overflow or respective owner