Search code examples
javagraphics2d

Graphics2d draw text with partial bold text


I was wondering if I can make a partial bold text for example:

Please make your assignment before 21 of july

I have not tried anything yet, because i just have no clue how to do this.

Here is my code currently for rendering text:

public void renderText(int page, String text, String font, int fontSize, Color color, int width, int height) {
       final Graphics2D g;
       if (page == 1) {
           g = (Graphics2D) outsideFlyer.getGraphics();
           g.drawImage(outsideFlyer, 0, 0, null);
       } else {
           g = (Graphics2D) insideFlyer.getGraphics();
           g.drawImage(insideFlyer, 0, 0, null);
       }
       if (font == null) {
           g.setFont(new Font(font, Font.PLAIN, fontSize));
       } else if ("bold".equals(font)) {
           g.setFont(new Font(null, Font.BOLD, fontSize));
       } else {
           g.setFont(new Font(font, Font.PLAIN, fontSize));
       }
       g.setColor(color);
       for (String txt : text.split("\n")) {
           g.drawString(txt, width, height += g.getFontMetrics().getHeight());
       }
       g.dispose();
   }

Is it possible to split the text in some way? I would love to have something like what happens on a lot of websites like everything inbetween * gets bold or in some way.


Solution

  • I ran into the same issue. After some research in other posts as well, I figured out a solution(at least it solved my problem).

    First, as far as I know, you can't do it in the same string, so you have to split it and draw them separately.

    Second, you need to get the width/height(depending on your case) that the first string occupies in your scenario. You can use your Graphics2D instance to get it, given your font, font size, etc. Then you can use this information to calculate the according position of the second string.

    Code example:

    String plainText = "Please make your assignment before ";
    String boldText = "21 of july";
    Graphics2D graphics2D = g; //will assume that you already configured it your way
    g.setFont(yourPlainFont);
    g.drawString(plainText, positionX, positionY);
    int plainTextSize = g.getFontMetrics().stringWidth(plainText);
    g.setFont(yourBoldFont);
    g.drawString(boldText, positionX + plainTextSize, positionY);
    

    Please note that this example is only considering a text in the same line, as asked by OP. You should be able to do the same in different lines(heights) as well, although I didn't test that way. Hope it helps.