• Post Reply Bookmark Topic Watch Topic
  • New Topic

Clip text in Rectangle  RSS feed

 
Sarone Thach
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi there,
I have drawn a Rectangle by using the Graphics.drawRect(x, y, width, height) method.
I have centered a text in this rectangle, by using Graphics.drawString.
How do I clip the text if it does not fit the rectangle?
thanks,
Sarone

[ December 09, 2003: Message edited by: Sarone Thach ]
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Sarone.
Just an idea:
totalWidth = 0
Get the width of the Rectangle (rw).
Set the font on the Graphics object (g)
Get the awt.FontMetrics for g.
Get the width of the first character (w) in the String by FontMetrics.charWidth(char).
If totalWidth + w is fewer than rw add the character to the string to display.
Do the same to the rest of the characters untill totalWidth is equal or greater that rw, or no more characters are left. Then draw the accumulated string to display.
 
Sarone Thach
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jose,
thanks for your suggestion. I have tried it and works fine.
Though i need the text to be centered. So for example if I wanted to display the word "New" in the rect and the rect is small only one letter can fit. Instead of displaying 'N' the middle letter 'e' is displayed.

I was hoping that it didn't have to come down to mathematics to figure out what I can display. I was hoping there is a Crop method somehere. In the case that only part of the 'e' can be displayed because the rect is really small. ie the 'e' is cropped on both ends.
Do you follow?
thanks
Sarone
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Graphics.clipRect(...) should be used. However Graphics.drawString(...) is failing to work with the clipped region. There is a bug report in Sun database. I am updating to the latest SDK to see if it was fixed...
[ December 13, 2003: Message edited by: Jose Botella ]
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No bug at all. Just a slip about coordinates :roll:
Here the first string appears cropped.

[ December 13, 2003: Message edited by: Jose Botella ]
[ December 13, 2003: Message edited by: Jose Botella ]
[ December 13, 2003: Message edited by: Jose Botella ]
 
Sarone Thach
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jose, you are a wonderful help. This is exactly what I'm after.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!