9

Hi all: I'm writing a class that inherit from TextView, and override its onDraw() method, but in the method, my invoke of canvas.drawText() doesn't seems to work, the code just like below:

protected void onDraw(Canvas canvas) {
    // super.onDraw(canvas);
    Paint paint = new Paint();
    paint.setColor(android.graphics.Color.WHITE);
    paint.setTextSize(20);

    String text = "hello";
    canvas.drawText(text, 0, 0, paint);
}
J.G.Sebring
  • 5,642
  • 1
  • 27
  • 42
Wenlin.Wu
  • 730
  • 1
  • 8
  • 17
  • @bemace, What does it do? This should draw hello in the upper left corner. Does it crash? Does it not do anything? Does the original behavior of textView take over? How are you using the Overridden TextView in a Layout? – Greg Giacovelli Oct 25 '10 at 06:04
  • @Greg - I just cleaned up the code formatting, user486005 asked the question – Brad Mace Oct 25 '10 at 16:39

2 Answers2

23

It isn't drawing anything because the text coordinates are bottom left. Since you're trying to draw on 0,0, it will draw above the screen.

Try changing the last line to:

canvas.drawText(text, 0, 20, paint);
dcarneiro
  • 6,720
  • 10
  • 46
  • 73
  • @user486005 When testing drawing its often best to try and draw to known point like 100,100 initially for debugging then worry about placement. You would have realized your issue was text drawing off the screen taking this approach. Just a thought. – ian.shaun.thomas Oct 17 '12 at 16:47
  • 4
    Why in the world would the coordinates start from bottom left? It has always been top left! – Andrii Chernenko Feb 14 '13 at 14:10
  • At least they could mention this difference in documentation! – Andrii Chernenko Feb 14 '13 at 14:11
  • doesn't work for me, In my case (kotlin) the method needs float values. I put 0f and 20f. Does it make any difference? – shurrok Dec 16 '19 at 09:26
-2

Excellent suggestions all around, great job guys really. Next time though it would be nice if you ask the guy in a comment or something whether or not he's tried the completely obvious before posting it as an answer. Do you really think that the second he got to a point that wasn't working he just came straight to Stack Overflow without experimenting?

I do have an alternate suggestion, that crazily enough is based on the entire question and not just the part that could be answered without much actual knowledge.

I would recommend trying your drawText call on a Canvas that's not in a TextView subclass as that way it won't be overridden by the several hundred lines of code in TextView that manage it's drawable state.

Justin Buser
  • 2,757
  • 22
  • 31