Fra TextLayout til String
HejJeg sidder og leger med lidt udskrivning.
Jeg ønsker at centre en tekst (som er længere end en linie - og derved skal centreres på to linier (håber i kan følge mig).
Jeg ved hvordan jeg får delt teksten op i to linier vha. TextLayout. Men når jeg så skal have centreret linie, har jeg brug for at få selve den tekst som ligger i TextLayout-objektet (for at kunne måle bredden af det).
Hvis det er til nogen hjælp er min kode følgende:
String titel = "HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH"
AttributedString paragraphText = new AttributedString (titel);
int hoejde = (int) fontMetrics.getHeight();
//--- Set the font for this text
paragraphText.addAttribute (TextAttribute.FONT, titelFont);
//--- Create a LineBreakMeasurer to wrap the text for
//the TextLayout object
LineBreakMeasurer lineBreaker = new LineBreakMeasurer (paragraphText.getIterator(), new FontRenderContext (null, true, true));
//--- Create the TextLayouts object
TextLayout layout;
TextLayout justifyLayout;
//--- Create a Vector to temporaly store each line of text
Vector lines = new Vector ();
//--- Get the output of the LineBreakMeasurer and store it in a
//Vector
while ((layout = lineBreaker.nextLayout ((float) width)) != null)
{
lines.add (layout);
}
//--- Scan each line of the paragraph and justify it except for
//the last line
for (int i = 0; i < lines.size (); i++)
{
//--- Get the line from the vector
layout = (TextLayout) lines.get (i);
//--- Check for the last line. When found print it
//--- with justification off
if (i != lines.size () - 1)
{
justifyLayout = layout.getJustifiedLayout
((float) width);
}
else
{
justifyLayout = layout;
}
//finder x-koordinatet for teksten
int titelX = (int)((pf.getImageableWidth () / 2) - (fontMetrics.stringWidth(*****)) / 2);
justifyLayout.draw (g2d, (float) titelX, (float) hoejde);
fontMetrics = g2d.getFontMetrics(g2d.getFont());
hoejde += fontMetrics.getHeight();
}
***** = her skal jeg bruge selve teksten (String) i justifyLayout for at kunne finde bredden.
Håber i kan følge hvad jeg mener - er lidt svært at foklare :-)
