javafontsgraphics2d

How to add multiple fonts to a string drawn by an Graphics2D object


I have a Graphics2D object and I want to use its drawString method. I can call that method and pass a String and (x, y) positions, which is very nice. However, I also have the possibility to change the font of my Graphics2D object, using the setFont method, which expects a Font object. This is also very nice. Unfortunately this is not enough for me, because I intend to define multiple font texts to my Font object.

This is the textual representation I would like to transfer to my Font object:

font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif

I have seen that I have the possibility to use the AttributedCharacterIterator interface to solve my problem, however, I am not sure how should I use that. I have seen that there is actually an implementation called AttributedString, which has a set of Attributes, but I am not sure how could I create an AttributedString object which could be used by the constructor of Font in such a way that my Graphics2D object will recognize the multiple fonts and apply them when I call drawString.

EDIT:

    public static AttributedString getFontByAttributes(String atts, String value)
    {
        String[] attributes = atts.split(",");
        AttributedString attributedString = new AttributedString(value);
        for (int attributeIndex = 0; attributeIndex < attributes.length; attributeIndex++)
        {
            attributedString.addAttribute(TextAttribute.FONT, attributes[attributeIndex].trim());
        }
        return attributedString;
    }
//...
    public void drawTitle(Graphics2D g2d)
{
//...
        g2d.drawString(getFontByAttributes(Settings.titleFontString, Settings.title).getIterator(), Settings.headerWidthOffset, Settings.headerHeightOffset);
//...
}

In the code above I have tried with Andale Mono, which is known on the system where I test this application, however, in the generated graphics, the text is drawn in Times New Roman font. Something is wrong and unfortunately I don't have a clue about what could I be missing.


Solution

  • Graphics2D has a drawString(AttributedCharacterIterator, int, int) method that you'll want to use.

    Simply build up your AttributedString with all the different TextAttribute.FONT properties you want for each specific sub-range of the string, then call:

    g2d.drawString(myAttributedString.getIterator(), x, y);