Skip to content

Commit 1a8bfa2

Browse files
authored
Performance: Only call getFontMetrics when required in Java2DRenderer (#106)
In my profilings, this method showed up as quite expensive.
1 parent 7a025f6 commit 1a8bfa2

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

src/main/java/uk/org/okapibarcode/output/Java2DRenderer.java

+7-4
Original file line numberDiff line numberDiff line change
@@ -112,8 +112,6 @@ public void render(Symbol symbol) {
112112
TextAlignment alignment = (text.alignment == JUSTIFY && text.text.length() == 1 ? CENTER : text.alignment);
113113
Font font = (alignment != JUSTIFY ? f : addTracking(f, text.width * magnification, text.text, g2d));
114114
g2d.setFont(font);
115-
FontMetrics fm = g2d.getFontMetrics();
116-
Rectangle2D bounds = fm.getStringBounds(text.text, g2d);
117115
float y = (float) (text.y * magnification) + marginY;
118116
float x;
119117
switch (alignment) {
@@ -122,10 +120,10 @@ public void render(Symbol symbol) {
122120
x = (float) ((magnification * text.x) + marginX);
123121
break;
124122
case RIGHT:
125-
x = (float) ((magnification * text.x) + (magnification * text.width) - bounds.getWidth() + marginX);
123+
x = (float) ((magnification * text.x) + (magnification * text.width) - getBounds(text, g2d).getWidth() + marginX);
126124
break;
127125
case CENTER:
128-
x = (float) ((magnification * text.x) + (magnification * text.width / 2) - (bounds.getWidth() / 2) + marginX);
126+
x = (float) ((magnification * text.x) + (magnification * text.width / 2) - (getBounds(text, g2d).getWidth() / 2) + marginX);
129127
break;
130128
default:
131129
throw new OkapiInternalException("Unknown alignment: " + alignment);
@@ -155,6 +153,11 @@ public void render(Symbol symbol) {
155153
g2d.setColor(oldColor);
156154
}
157155

156+
private static Rectangle2D getBounds(TextBox text, Graphics2D g2d) {
157+
FontMetrics fm = g2d.getFontMetrics();
158+
return fm.getStringBounds(text.text, g2d);
159+
}
160+
158161
private static Ellipse2D.Double adjust(Circle circle, double magnification, int marginX, int marginY) {
159162
double x = marginX + ((circle.centreX - circle.radius) * magnification);
160163
double y = marginY + ((circle.centreY - circle.radius) * magnification);

0 commit comments

Comments
 (0)