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

2012/9/18

Load Font from .tff file

SPower SPower

2012/9/18

#
Hi all, I want to load a Font from a .tff file, so I can draw text on a GreenfootImage with another font. I tried some things, but I can't seem to get it working. Can anybody help? Thanks.
GregC246 GregC246

2012/9/18

#
This code uses Vdj.ttf in my projectname/resources folder to create a font of size 24.
Font font = new Font("q",0,0);
        InputStream is = Glo.class.getResourceAsStream("resources/Vdj.ttf");//location in project folder
        Font uniFont = null;
           try {

            uniFont=Font.createFont(Font.TRUETYPE_FONT,is);
         }
        catch(java.awt.FontFormatException r){
            System.err.println("FontFormatException: " + r.getMessage());

        }
        catch(java.io.IOException r){
            System.err.println("FontFormatException: " + r.getMessage());

        }
       font = uniFont.deriveFont(24f);//desired font size
This code does not work with web applets, and nobody else on the forums seems to know how to do that (I've asked twice). However, it does work with stand-alone executible .jars.
SPower SPower

2012/9/18

#
Thank you! It works! I don't know why my versions didn't work, but it doesn't matter. And if you wanna let it work in an applet, you have to use the URL class, a little example:
URL url = new URL(getCodeBase(), "resources/Vdj.ttf");
I don't know the Font API at the top of my head, but maybe it helps.
You need to login to post a reply.