2

I want to draw a second string adjacent to first string on the screen canvass. The starting point of the second string should be the width of the first string.I used paint.measuretext() method of Android. But it returns the width which is lesser than the actual width. So my second String overlaps the first one. Can any body explain how to get the accurate width of a string?

testString1 = "44444444444444444444444444444444444444444";
testString2 = "Sample Test String";
canvas.drawText(testString1,0,50, paint);
int textWidth = (int)paint.measureText(testString1);
canvas.drawText(testString2,textWidth,50, paint);
Gangnus
  • 24,044
  • 16
  • 90
  • 149
AndosBerry
  • 145
  • 1
  • 12

1 Answers1

0

measuretext() is the more precise measurer. So, you have changed text itself or font or font size or something else between measuring and drawing.

Look also here for other methods of measurement. But don't wait for much - measuretext IS a good measurer and the mistake almost surely is on your side.

New Edit: Check the same function for string1+string1 - if the result will be 2x the previous? If yes - that means that you are awaiting the result in one units and you are getting them in the other ones. (measuretext works in scaled pixels). And maybe paint or canvas use different measures for setting x,y and for text measure.

Edit 2: The incorrect scaling can be defined by emulator. Try different resolution/screen sizes there. If it influences the result, you should find the Paint/Canvas parameter by which you can compensate the screen resolution influence.

Community
  • 1
  • 1
Gangnus
  • 24,044
  • 16
  • 90
  • 149
  • measuretext returns wrong measurements.The string is "44444444444444444444444444444444444444444". – AndosBerry Jan 10 '12 at 06:48
  • Could you put your code in the question, please? How could we search for an error being blind? – Gangnus Jan 10 '12 at 09:20
  • testString1 = "44444444444444444444444444444444444444444"; testString2 = "Sample Test String"; canvas.drawText(testString1,0,50, paint); int textWidth = (int)paint.measureText(testString1); canvas.drawText(testString1,textWidth,50, paint); – AndosBerry Jan 10 '12 at 10:45
  • That 50 is not the string length.That is y point from which the string has to be drawn.x point will be the length of the string which is textWidth – AndosBerry Jan 11 '12 at 05:42
  • I have added one more possibility to the answer – Gangnus Jan 11 '12 at 14:33