|
| 1 | +package com.baeldung.asciiart; |
| 2 | + |
| 3 | +import java.awt.Font; |
| 4 | +import java.awt.Graphics; |
| 5 | +import java.awt.Graphics2D; |
| 6 | +import java.awt.RenderingHints; |
| 7 | +import java.awt.image.BufferedImage; |
| 8 | + |
| 9 | +public class AsciiArt { |
| 10 | + |
| 11 | + public AsciiArt() { |
| 12 | + } |
| 13 | + |
| 14 | + public void drawString(String text, String artChar, Settings settings) { |
| 15 | + BufferedImage image = getImageIntegerMode(settings.width, settings.height); |
| 16 | + |
| 17 | + Graphics2D graphics2D = getGraphics2D(image.getGraphics(), settings); |
| 18 | + graphics2D.drawString(text, 6, ((int) (settings.height * 0.67))); |
| 19 | + |
| 20 | + for (int y = 0; y < settings.height; y++) { |
| 21 | + StringBuilder stringBuilder = new StringBuilder(); |
| 22 | + |
| 23 | + for (int x = 0; x < settings.width; x++) { |
| 24 | + stringBuilder.append(image.getRGB(x, y) == -16777216 ? " " : artChar); |
| 25 | + } |
| 26 | + |
| 27 | + if (stringBuilder.toString() |
| 28 | + .trim() |
| 29 | + .isEmpty()) { |
| 30 | + continue; |
| 31 | + } |
| 32 | + |
| 33 | + System.out.println(stringBuilder); |
| 34 | + } |
| 35 | + |
| 36 | + } |
| 37 | + |
| 38 | + private BufferedImage getImageIntegerMode(int width, int height) { |
| 39 | + return new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); |
| 40 | + } |
| 41 | + |
| 42 | + private Graphics2D getGraphics2D(Graphics graphics, Settings settings) { |
| 43 | + graphics.setFont(settings.font); |
| 44 | + |
| 45 | + Graphics2D graphics2D = (Graphics2D) graphics; |
| 46 | + graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); |
| 47 | + |
| 48 | + return graphics2D; |
| 49 | + } |
| 50 | + |
| 51 | + public class Settings { |
| 52 | + public Font font; |
| 53 | + public int width; |
| 54 | + public int height; |
| 55 | + |
| 56 | + public Settings(Font font, int width, int height) { |
| 57 | + this.font = font; |
| 58 | + this.width = width; |
| 59 | + this.height = height; |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments