Advertisement
Guest User

Untitled

a guest
Jun 20th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. // CLEAR BACKGROUND
  2. g.setColor(Color.DARK_GRAY);
  3. g.fillRect(0, 0, w, h);
  4.  
  5. // ACTIVATE ANTIALIASING AND FRACTIONAL METRICS
  6. g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  7. g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
  8.  
  9. // PREPARE TEXT, COLOR
  10. final String text = "The Higgs Boson is ...";
  11. g.setColor(Color.ORANGE);
  12.  
  13. // CREATE GLYPHVECTOR FROM TEXT, CREATE PRELIMINARY SHAPE FOR COORDINATE CALCULATION, CALC COORDINATES
  14. final GlyphVector gv = yourFont.createGlyphVector(g.getFontRenderContext(), text);
  15. final Rectangle2D stringBoundsForPosition = gv.getOutline().getBounds2D();
  16. final double xForShapeCreation = (w - stringBoundsForPosition.getWidth()) / 2d;
  17. final double yForShapeCreation = (h - stringBoundsForPosition.getHeight()) / 2d;
  18.  
  19. // DERIVE SHAPE AGAIN, THIS TIME IN THE RIGHT PLACE (IT'S NOT THE ONLY POSSIBLE METHOD.)
  20. final Shape textShape = gv.getOutline((float) xForShapeCreation, (float) yForShapeCreation + g.getFontMetrics(yourFont).getAscent());
  21. g.fill(textShape);
  22.  
  23. // GET PRECISE SHAPE BOUNDS, TURN OFF ANTIALIASING FOR HIGHER VISUAL PRECISION OF THE LINES
  24. final Rectangle2D stringBoundsForEverything = textShape.getBounds2D();// JavaDocs: "Returns a high precision [...] bounding box of the Shape [...] guarantee [...] that the Shape lies entirely within the indicated Rectangle2D."
  25. g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
  26.  
  27. // DRAW RECTANGLE BORDER
  28. final double borderDistance = 10d;
  29. final Shape borderRect = new Rectangle2D.Double(stringBoundsForEverything.getX() - borderDistance * 2, stringBoundsForEverything.getY() - borderDistance, stringBoundsForEverything.getWidth() + borderDistance * 4, stringBoundsForEverything.getHeight() + borderDistance * 2);
  30. g.setStroke(new BasicStroke(3f));
  31. g.draw(borderRect);
  32.  
  33. // DRAW THIN TIGHT RECTANGLE BORDER
  34. final Shape borderRectTight = new Rectangle2D.Double(stringBoundsForEverything.getX(), stringBoundsForEverything.getY(), stringBoundsForEverything.getWidth(), stringBoundsForEverything.getHeight());
  35. g.setStroke(new BasicStroke(1f));
  36. g.setColor(Color.GRAY);
  37. g.draw(borderRectTight);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement