Skip to content

Instantly share code, notes, and snippets.

@codebucketdev
Created May 24, 2015 15:47
Show Gist options
  • Save codebucketdev/6f9f513ea6d774a0edc2 to your computer and use it in GitHub Desktop.
Save codebucketdev/6f9f513ea6d774a0edc2 to your computer and use it in GitHub Desktop.
Modified Font.java from PixEngine made by Majoolwip
package org.j2game.graphics;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.swing.JPanel;
public class Font
{
private static final int NUM_UNICODES = 59;
public int[] offsets = new int[NUM_UNICODES];
public int[] widths = new int[NUM_UNICODES];
public Image image;
public Font(String path)
{
this(new Image(path));
}
public Font(File file)
{
this(new Image(file));
}
public Font(Image image)
{
this.image = image;
int unicode = -1;
for(int x = 0; x < image.width; x++)
{
Color color = image.pixels[x];
if(color.value == 0xff0000ff)
{
unicode++;
offsets[unicode] = x;
}
if(color.value == 0xffffff00)
{
widths[unicode] = x - offsets[unicode];
}
}
}
public static Font createFont(String fontName, int fontSize)
{
// Create Font instance
java.awt.Font font = new java.awt.Font(fontName, java.awt.Font.PLAIN, fontSize);
// Calculate width of sprite
int width = 0, height = 0;
FontMetrics metrics = new JPanel().getFontMetrics(font);
for (int c = 32; c < 91; c++)
{
width += metrics.charWidth((char) c) + 2;
}
// Calculate height and offset of sprite due to wrong height of chars like '(', ')' or 'Q'
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
Graphics2D gr = img.createGraphics();
int lastOffset = fontSize;
for (int c = 32; c < 91; c++)
{
FontRenderContext frc = gr.getFontRenderContext();
GlyphVector gv = font.createGlyphVector(frc, String.valueOf((char) c));
Rectangle bounds = gv.getPixelBounds(null, 0, 0);
int offset = fontSize - bounds.height;
if (offset > 0 && offset <= lastOffset)
{
lastOffset = offset;
}
}
height = fontSize + lastOffset + 1;
fontSize -= lastOffset;
// Create sprite image and get the Graphics to draw
BufferedImage sprite = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = sprite.createGraphics();
graphics.setColor(java.awt.Color.MAGENTA);
graphics.fillRect(0, 0, width, height);
// "Drawer" position
int x = 0, y = 0;
graphics.setFont(font);
for (int c = 32; c < 91; c++)
{
y = 0;
graphics.setColor(java.awt.Color.BLUE);
graphics.drawLine(x, y, x, y);
x++;
y = 1;
graphics.setColor(java.awt.Color.WHITE);
graphics.drawString(String.valueOf((char) c), x, y + fontSize);
x += metrics.charWidth((char) c);
y = 0;
graphics.setColor(java.awt.Color.YELLOW);
graphics.drawLine(x, y, x, y);
x++;
}
return new Font(new Image(sprite));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment