1

I have a requirement to draw using the method .drawString from Graphics2D (java.awt) a text in arabic. But when I use the method using the following code it will just show a bunch of empty squares

BufferedImage bufferedImage = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = bufferedImage.createGraphics();
graphics.drawString("مرحبا هذا نص عربي",
                        xStartText, endY + smallRectHeight);

The resulted output

Can somebody help? I've search for code snippets to solve this problem but I could not find anything out there?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
JohnM
  • 13
  • 2
  • try encoding the string with a different standard – Alberto Sinigaglia Jun 02 '21 at 17:53
  • @Berto99 I recently faced this problem too, unfornunately could not solve it yet. But I tried encoding the text in UTF-8 and it did not solve the issue. – Triple3XH Jun 02 '21 at 18:01
  • @Triple3XH have you tried using the encoded string instead of the "original" one? for example using https://www.browserling.com/tools/utf8-encode – Alberto Sinigaglia Jun 02 '21 at 18:02
  • 1
    maybe try `graphics.setFont(new Font("Arial", Font.PLAIN, 24));` or with any font that can display that characters - posted code worked perfectly for me (Java 16, default "Dialog" or "Monospaced" or "Aria" fonts) –  Jun 02 '21 at 18:14
  • Have you tried using a JFrame to show text? – FairOPShotgun Jun 03 '21 at 00:43

1 Answers1

0

Unless supplying a font (with the app.) that can support Arabic characters, best to find a suitable font at run-time.

I supplied Noto Sans Arabic as a font ..

Supplying the font is the most robust solution IMO. A couple of tips: See also the accepted answer to How do you import a font? & note the font will become an embedded resource by the time the app. is deployed. The info page for embedded resources provides tips on how to get a URL pointing to the font.

.. and it worked as desired.

Glad you got it sorted.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433