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.

86 lines
2.0 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 Color textColor = null;
  15. protected double textWidth, textHeight;
  16. Font serifFont = null;
  17. /** Constructor to intitialize the TextArtist attributes
  18. *
  19. * @param go GameObject to be used for xy coordinate reference
  20. * @param text the text to draw
  21. * @param size point size to be used for font "Serif"
  22. * @param textColor color to draw the text with (foreground)
  23. */
  24. public TextArtist(GameObject go, String text, int size, Color textColor) {
  25. super(go);
  26. this.text = text;
  27. this.serifFont = new Font("Serif", Font.PLAIN, size);
  28. FontRenderContext frc = new FontRenderContext(null, false, false);
  29. this.textWidth = (int) (serifFont.getStringBounds(text, frc).getWidth());
  30. this.textHeight = (int) (serifFont.getStringBounds(text, frc).getHeight());
  31. this.textColor = textColor;
  32. }
  33. public String getText() {
  34. return this.text;
  35. }
  36. public void setText(String s) {
  37. this.text = s;
  38. }
  39. public double getTextWidth() {
  40. return textWidth;
  41. }
  42. public void setTextWidth(double textWidth) {
  43. this.textWidth = textWidth;
  44. }
  45. public double getTextHeight() {
  46. return textHeight;
  47. }
  48. public void setTextHeight(double textHeight) {
  49. this.textHeight = textHeight;
  50. }
  51. /**
  52. * Draw the text.
  53. *
  54. * @param g The Swing graphics context.
  55. */
  56. @Override
  57. public void draw(Graphics2D g) {
  58. AttributedString as = new AttributedString(this.text);
  59. as.addAttribute(TextAttribute.FONT, this.serifFont);
  60. as.addAttribute(TextAttribute.FOREGROUND, this.textColor);
  61. g.drawString(as.getIterator(), (int) Math.round(this.getX() - this.textWidth / 2.),
  62. (int) Math.round(this.getY() + this.textHeight / 2.));
  63. }
  64. }