This site requires JavaScript, please enable it in your browser!
Greenfoot back
SammyFORreal
SammyFORreal wrote ...

2022/4/2

using TrueTypeFont for GreenfootImage

SammyFORreal SammyFORreal

2022/4/2

#
Hello. Im trying to use a .TTF font for my Project. I want to draw Strings on an GreenfootImage with it. However, GreenfootImage only accepts Greenfoot.Font & those doesnt accept custom font paths or java.awt.Font. There are already some topics like 2058, but they just create a java.awt.Font that, again, GreenfootImage doesnt accept. How can I use my font anyways?
SammyFORreal SammyFORreal

2022/4/2

#
Okay I found the solution by myself. By creating a new GreenfootFont, it just stores a java.awt.Font inside, which is private. So by simply doin' Reflections stuff, I'm able to load a font from a .TTF file. (Can't be .OTF!)
/* ... */
GreenfootImage img = new GreenfootImage(60*4, 49);
        greenfoot.Font font = new greenfoot.Font("Arial Black", false, false , 24);

        try {
            Field pFont = greenfoot.Font.class.getDeclaredField("font");
            pFont.setAccessible(true);

            Font uniFont = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream("resources/ka1.ttf")); /* PATH TO FONT from project root folder */
            uniFont = uniFont.deriveFont(20f); /* Set font size */

            pFont.set(font, uniFont); /* Replace font */
        } catch(NoSuchFieldException | IllegalAccessException | FontFormatException | IOException e) { /* Hopefully didn't forget to catch some errors lol */
            e.printStackTrace();
        }

        img.setFont(font);
/* ... */
You need to login to post a reply.