سؤال

I am facing a situation in which I need to draw bitmap for a given text. I tried to render a TextView with required properties and then draw its bitmap using canvas. My try looks like this:

TextView nameTv = new TextView(context);
Bitmap bmp = Bitmap.createBitmap(200, 200, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);

nameTv.layout(0, 0, 200, 200);
nameTv.setGravity(Gravity.CENTER);
nameTv.setText("Test");
nameTv.setBackgroundColor(Color.RED);

nameTv.draw(canvas);

The problem with this code is that the text on TextView not center aligned, which I require. Any suggestions are welcomed :)

Thanks, Ammar

هل كانت مفيدة؟

المحلول

I think the problem is in measuring. You not calling measure for that and it don't have properly size. Call nameTv.measure() before layout().

Call measure like this:

int measureSpecWidth = MeasureSpec.makeMeasureSpec(200, MeasureSpec.EXACTLY);
int measureSpecHeight = MeasureSpec.makeMeasureSpec(200, MeasureSpec.EXACTLY);
nameTv.measure(measureSpecWidth, measureSpecHeight);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top