1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 package org.microemu.device.j2se;
26
27 import java.awt.Font;
28 import java.awt.FontFormatException;
29 import java.awt.FontMetrics;
30 import java.awt.Graphics2D;
31 import java.awt.RenderingHints;
32 import java.awt.image.BufferedImage;
33 import java.io.IOException;
34 import java.net.URL;
35
36 import org.microemu.log.Logger;
37
38 public class J2SETrueTypeFont implements J2SEFont {
39
40 private final static Graphics2D graphics = (Graphics2D) new BufferedImage(1, 1,
41 BufferedImage.TYPE_INT_ARGB).getGraphics();
42
43 private URL url;
44
45 private String style;
46
47 private int size;
48
49 private boolean antialiasing;
50
51 private boolean initialized;
52
53 private FontMetrics fontMetrics;
54
55 public J2SETrueTypeFont(URL url, String style, int size, boolean antialiasing) {
56 this.url = url;
57 this.style = style.toLowerCase();
58 this.size = size;
59 this.antialiasing = antialiasing;
60
61 this.initialized = false;
62 }
63
64 public void setAntialiasing(boolean antialiasing) {
65 if (this.antialiasing != antialiasing) {
66 this.antialiasing = antialiasing;
67 initialized = false;
68 }
69 }
70
71 public int charWidth(char ch) {
72 checkInitialized();
73
74 return fontMetrics.charWidth(ch);
75 }
76
77 public int charsWidth(char[] ch, int offset, int length) {
78 checkInitialized();
79
80 return fontMetrics.charsWidth(ch, offset, length);
81 }
82
83 public int getBaselinePosition() {
84 checkInitialized();
85
86 return fontMetrics.getAscent();
87 }
88
89 public int getHeight() {
90 checkInitialized();
91
92 return fontMetrics.getHeight();
93 }
94
95 public int stringWidth(String str) {
96 checkInitialized();
97
98 return fontMetrics.stringWidth(str);
99 }
100
101 public Font getFont() {
102 checkInitialized();
103
104 return fontMetrics.getFont();
105 }
106
107 private synchronized void checkInitialized() {
108 if (!initialized) {
109 int awtStyle = 0;
110 if (style.indexOf("plain") != -1) {
111 awtStyle |= Font.PLAIN;
112 }
113 if (style.indexOf("bold") != -1) {
114 awtStyle |= Font.BOLD;
115 }
116 if (style.indexOf("italic") != -1) {
117 awtStyle |= Font.ITALIC;
118 }
119 if (style.indexOf("underlined") != -1) {
120
121 }
122 if (antialiasing) {
123 graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
124 } else {
125 graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
126 }
127
128 try {
129 Font baseFont = Font.createFont(Font.TRUETYPE_FONT, url.openStream());
130 fontMetrics = graphics.getFontMetrics(baseFont.deriveFont(awtStyle, size));
131 initialized = true;
132 } catch (FontFormatException ex) {
133 Logger.error(ex);
134 } catch (IOException ex) {
135 Logger.error(ex);
136 }
137 }
138 }
139
140 }