title: Using an affline transformation to set font size to be proportional to its container in Swing
body: <p>So, slightly different than similar questions on SO but any insight in how I would use an affline transformation to shrink or grow a text string so that the overall size is proportional to the region it's to be drawn on?</p>
  
  <p>For example, I'd like the font to be 50% of the width of the region.</p>
  
  <p>I've inherited some code like this but I don't really understand what its doing </p>
  
  <pre><code>Font font = new Font("Arial", Font.BOLD, 12);
  FontRenderContext context = graphics.getFontRenderContext();
  graphics.setFont(font);
  Rectangle2D bounds = graphics.getFont().getStringBounds("Hello world", context);
  
  LineMetrics line = font.getLineMetrics(text, context);
  float xScale = (float) (region.width / bounds.getWidth());
  float yScale = (region.height / (line.getAscent() + line.getDescent()));
  
  double x = region.x;
  double y = region.y + region.height - (yScale * line.getDescent());
  AffineTransform transformation = AffineTransform.getTranslateInstance(x, y);
  
  if (xScale &gt; yScale)
      transformation.scale(yScale, yScale);
  else
      transformation.scale(xScale, xScale);
  
  graphics.setFont(font.deriveFont(transformation));
  graphics.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON);
  
  int centerX = region.width / 2;
  int centerY = region.height / 2;
  graphics.drawString(text, centerX, centerY - (int) bounds.getHeight());
  </code></pre>
  
  <p>It seems to set the size to something reasonable but not center this in the region. If you can shed light on what its <em>trying</em> to do, that'd be great.</p>
  
  <p>Any pointers (as long as they're not literally pointers to the java font tutorial) much appreciated.            </p>