You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
1.8 KiB

  1. package rendering;
  2. import gameobjects.GameObject;
  3. import java.awt.Color;
  4. import java.awt.Font;
  5. import java.awt.Graphics2D;
  6. import java.awt.font.FontRenderContext;
  7. import java.awt.font.TextAttribute;
  8. import java.text.AttributedString;
  9. /**
  10. * Rendering an object as a text of a specified color, size and font.
  11. */
  12. public class TextArtist extends Artist {
  13. private String text = null;
  14. private int size = 1;
  15. private Color textColor = null;
  16. protected double textWidth, textHeight;
  17. Font serifFont = null;
  18. public TextArtist(GameObject go, String text, int size, Color textColor) {
  19. super(go);
  20. this.size = size;
  21. this.text = text;
  22. this.serifFont = new Font("Serif", Font.PLAIN, size);
  23. FontRenderContext frc = new FontRenderContext(null, false, false);
  24. this.textWidth = (int) (serifFont.getStringBounds(text, frc).getWidth());
  25. this.textHeight = (int) (serifFont.getStringBounds(text, frc).getHeight());
  26. this.textColor = textColor;
  27. }
  28. public String getText() {
  29. return this.text;
  30. }
  31. public void setText(String s) {
  32. this.text = s;
  33. }
  34. public double getTextWidth() {
  35. return textWidth;
  36. }
  37. public void setTextWidth(double textWidth) {
  38. this.textWidth = textWidth;
  39. }
  40. public double getTextHeight() {
  41. return textHeight;
  42. }
  43. public void setTextHeight(double textHeight) {
  44. this.textHeight = textHeight;
  45. }
  46. /**
  47. * Draw the text.
  48. *
  49. * @param g The Swing graphics context.
  50. */
  51. @Override
  52. public void draw(Graphics2D g) {
  53. AttributedString as = new AttributedString(this.text);
  54. as.addAttribute(TextAttribute.FONT, this.serifFont);
  55. as.addAttribute(TextAttribute.FOREGROUND, this.textColor);
  56. g.drawString(as.getIterator(), (int) Math.round(this.getX() - this.textWidth / 2.),
  57. (int) Math.round(this.getY() + this.textHeight / 2.));
  58. }
  59. }