Skip to content

Commit 25a118d

Browse files
ochejapivovarit
authored andcommitted
Implement examples for ASCII Art in Java (eugenp#3753)
1 parent 642d7c2 commit 25a118d

2 files changed

Lines changed: 82 additions & 0 deletions

File tree

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.baeldung.asciiart;
2+
3+
import java.awt.Font;
4+
5+
import org.junit.Test;
6+
7+
import com.baeldung.asciiart.AsciiArt.Settings;
8+
9+
public class AsciiArtTest {
10+
11+
@Test
12+
public void givenTextWithAsciiCharacterAndSettings_shouldPrintAsciiArt() {
13+
AsciiArt asciiArt = new AsciiArt();
14+
String text = "BAELDUNG";
15+
Settings settings = asciiArt.new Settings(new Font("SansSerif", Font.BOLD, 24), text.length() * 30, 30); // 30 pixel width per character
16+
17+
asciiArt.drawString(text, "*", settings);
18+
}
19+
20+
}

0 commit comments

Comments
 (0)