Skip to content

Commit

Permalink
Performance: Only call getFontMetrics when required in `Java2DRende…
Browse files Browse the repository at this point in the history
…rer` (#106)

In my profilings, this method showed up as quite expensive.
  • Loading branch information
uwolfer authored Mar 14, 2024
1 parent 7a025f6 commit 1a8bfa2
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions src/main/java/uk/org/okapibarcode/output/Java2DRenderer.java
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,6 @@ public void render(Symbol symbol) {
TextAlignment alignment = (text.alignment == JUSTIFY && text.text.length() == 1 ? CENTER : text.alignment);
Font font = (alignment != JUSTIFY ? f : addTracking(f, text.width * magnification, text.text, g2d));
g2d.setFont(font);
FontMetrics fm = g2d.getFontMetrics();
Rectangle2D bounds = fm.getStringBounds(text.text, g2d);
float y = (float) (text.y * magnification) + marginY;
float x;
switch (alignment) {
Expand All @@ -122,10 +120,10 @@ public void render(Symbol symbol) {
x = (float) ((magnification * text.x) + marginX);
break;
case RIGHT:
x = (float) ((magnification * text.x) + (magnification * text.width) - bounds.getWidth() + marginX);
x = (float) ((magnification * text.x) + (magnification * text.width) - getBounds(text, g2d).getWidth() + marginX);
break;
case CENTER:
x = (float) ((magnification * text.x) + (magnification * text.width / 2) - (bounds.getWidth() / 2) + marginX);
x = (float) ((magnification * text.x) + (magnification * text.width / 2) - (getBounds(text, g2d).getWidth() / 2) + marginX);
break;
default:
throw new OkapiInternalException("Unknown alignment: " + alignment);
Expand Down Expand Up @@ -155,6 +153,11 @@ public void render(Symbol symbol) {
g2d.setColor(oldColor);
}

private static Rectangle2D getBounds(TextBox text, Graphics2D g2d) {
FontMetrics fm = g2d.getFontMetrics();
return fm.getStringBounds(text.text, g2d);
}

private static Ellipse2D.Double adjust(Circle circle, double magnification, int marginX, int marginY) {
double x = marginX + ((circle.centreX - circle.radius) * magnification);
double y = marginY + ((circle.centreY - circle.radius) * magnification);
Expand Down

0 comments on commit 1a8bfa2

Please sign in to comment.