Reputation: 89626
I'm implementing a custom View
, and I need to draw some text in it. The text has to fit in a box (so I have to break it up and make it fit). Because of this, I thought I could use a TextView
and draw it inside my custom View
. Here's what I've tried:
canvas.drawRoundRect(rect, eventRadius, eventRadius, eventBg);
canvas.save();
canvas.clipRect(rect);
TextView tv = new TextView(getContext());
tv.setText(e.getSummary());
tv.setTextColor(Color.BLACK);
tv.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
tv.layout(0, 0, (int) (rect.right - rect.left), (int) (rect.bottom - rect.top));
tv.draw(canvas);
canvas.restore();
However, nothing is showing up. I know rect
is OK because the first drawRoundRect
works fine. What am I missing? Is there a better way? Maybe I should extend ViewGroup
instead? I'm not sure how that would work.
Upvotes: 2
Views: 1662
Reputation: 7350
To do it without wrapping:
canvas.drawText(yourText, xCoord,YCoord, YourPaint);
to do it with wrapping
protected void onDraw(Canvas canvas) {
TextPaint tp=new TextPaint();
tp.setARGB(255, 255, 0, 0);
tp.setTextSize(12);
StaticLayout sl=new StaticLayout("THIS IS SOME LONGER TEXT",tp,60,Layout.Alignment.ALIGN_NORMAL,1f,0f,true);
sl.draw(canvas);
}
http://developer.android.com/reference/android/text/StaticLayout.html
Upvotes: 3
Reputation: 89626
My current solution is this:
TextView textView = new TextView(getContext());
int width = (int) (rect.right - rect.left);
int height = (int) (rect.bottom - rect.top);
textView.layout(0, 0, width, height);
textView.setText(e.getSummary());
Bitmap bitmapText = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvasText = new Canvas(bitmapText);
textView.draw(canvasText);
canvas.drawBitmap(bitmapText, rect.left, rect.top, null);
It feels dirty (and somewhat un-optimal), but it works. If someone doesn't come up with a better solution I'm going to mark this as accepted in a couple of days.
Upvotes: 0