Java Write Text Image with Specific Fonts - java

I'm writing some text on top of an existing image and the font isn't very sharp. Is there some settings either with the Graphics2D or Font classes that help make fonts look nicer when writing text on top of images? The Dante font doesn't come out as Dante when I write it. I've tried to use antialiasing but it had no effect (see setRenderingHint). The images came out the same with or without the RenderingHint set. Any suggestions?
public class ImageCreator{
public void createImage(String text){
Graphics2D g = img.createGraphics(); //img is a BufferedImage read in from file system
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
Font fnt=new Font("Dante",1,20);
Color fntC = new Color(4, 4, 109);
g.setColor(fntC);
g.setFont(fnt);
Dimension d = new Dimension(200, 113);
drawCenteredString(text, d.width, d.height, g);
}
public static void drawCenteredString(String s, int w, int h, Graphics g) {
FontMetrics fm = g.getFontMetrics();
int x = (w - fm.stringWidth(s)) / 2;
int y = (fm.getAscent() + (h - (fm.getAscent() + fm.getDescent())) / 2);
g.drawString(s, x, y);
}
}

Use TextLayout, as shown here.
Addendum: The advantage of TextLayout is that RenderingHints may be applied to the FontRenderContext.

Related

Text doesnot rotate Graphics2D

I checked on site and followed all examples.
I have written the code, the position, font of text changes but the angle or rotation doesnt take place. Any help advice pointers are much appreciated
int x = X;
int y = Y;
int w = 9;
int h = 9;
int fontsize = 7;
Rectangle bounds = new java.awt.Rectangle(x, y, w, h);
ShapeGroup group = new ShapeGroup();
group.setAnchor(bounds);
slide.addShape(group);
Graphics2D graphics = new PPGraphics2D(group);
AffineTransform affineTransform = new AffineTransform();
affineTransform.rotate(50);
java.awt.Shape circle = new Ellipse2D.Float(x, y, 9, 9);
graphics.draw(circle);
graphics.setPaint(colorRating);
graphics.fill(circle);
//graphics.rotate(-Math.PI/2);
graphics.setColor(new Color(159, 78, 15));
Font font = new Font("Arial", Font.BOLD, fontsize);
Font rotatedFont = font.deriveFont(affineTransform);
graphics.setFont(rotatedFont);
graphics.setTransform(affineTransform);
graphics.drawString(siteName, x + 11, y + fontsize + 1);
graphics.setFont(font);
I reported a similar bug to vldocking project: when used on MacOS, tab titles didn’t rotate 90° when the tabs were on the left/right. After investigating further, I submitted a patch, which amounted to one line:
graphics.setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
Without antialiasing, the text rendering took an optimized path, which skipped the ability to rotate the glyphs.
I don’t know if you are on a MacOS, with the same java implementation. Try setting the antialiasing attribute, and if that doesn’t work, some other rendering hints as well.
Good luck!

Making text width flexible with ttf font

I am inquiring about two things. First I am having an ttf file and it is located in my macair drive. I do not want to add that file into my project structure. How can i import the True_type font from it. I have tried various ways to import it my Java program. e.g. public class TextFixer {
private static String[] names = { "iksswgrg.ttf" }; //this exists on my macair drive and i want to create font from it.
private static Map<String, Font> cache = new ConcurrentHashMap<String, Font>(names.length);
static {
for (String name : names) {
cache.put(name, getFont(name));
}
}
public static Font getFont(String name) {
Font font = null;
if (cache != null) {
if ((font = cache.get(name)) != null) {
return font;
}
}
String fName = "/fonts/" + name;
try {
InputStream is = TextFixer.class.getResourceAsStream(fName);
font = new Font("ttf", 0, 16);
//font = Font.createFont(Font.TRUETYPE_FONT, is);
} catch (Exception ex) {
ex.printStackTrace();
System.err.println(fName + " not loaded. Using serif font.");
font = new Font("serif", Font.PLAIN, 24);
}
return font;
}
2nd part is I want to create a String by using Graphics. First I need to have width that is of 130mm. The height of the displayed box will be the tallest character in the provided string. The font size is between 8 and 16. I have an enterprise project which take care of the height and size of the ttf. The problem i face is: I do not want to use swing/javafx libraries. I want to use Graphics library of Java, use Graphics2D to have a rectangle. How can i set its width to be precisely 130mm? Then I want to make that width flexible with according to the Font. I want to draw a string and the string should get adjusted/being flexible in the provided width. I am able to draw a string through g.drawString() but I am unable to see it on console. As I do not want to use Jframe or any Swing/javaFX libraries.
I know this seems a bit long but I hope I have explained it well enough. I desperately need help. Please let me know if you guys can help me out here.
Thanks in advance
First I am having an ttf file and it is located in my macair drive. I do not want to add that file into my project structure. How can i import the True_type font from it
This is more of a problem to do with "How do you reference a file on the file system" then "How do I load a font", because if you can solve the first, you can solve the second.
File fontFile = new File("some/relative/path/to/your/Font.tff");
or
File fontFile = new File("/some/absolute/path/to/your/Font.tff");
Personally, I like neither, as it it causes too much trouble (working directories, other systems, etc), I prefer to use embedded resources where possible or put the files in a common location.
For example {user.home}/AppData/Local/{application name} on Windows or on Mac you could use {user.home}/Library/Application Support/{application name}, then it doesn't matter where the program is executed from
Loading the font is relatively simple. For my example, I placed the font file in the working directory of the program
System.out.println(new File("Pacifico.ttf").exists());
Font font = Font.createFont(Font.TRUETYPE_FONT, new File("Pacifico.ttf"));
2nd part is I want to create a String by using Graphics. First I need to have width that is of 130mm. The height of the displayed box will be the tallest character in the provided string
This is much more complicated, as images are measured in pixels. In order to know how many pixels make up a given distance, we need to know the DPI of the image.
its 72DPI
Okay then, from that, we can calculate the number of pixels we need
public static double cmToPixel(double cm, double dpi) {
return (dpi / 2.54) * cm;
}
130mm (13 cm) comes out to be 368.503937007874 # 72dpi.
From this, we need to find the font point size for a given piece of text to fit within this range.
Now, there are a number of was you can do this, you could simply start at point 1 and perform a linear progression till you pass the range you're after. It's not exactly fast and, as you increase the size, it can become a little error prone.
I've opted for more of a divide and conquer approach
protected static int widthOfText(String text, Font font, float fontSize, Graphics2D g2d) {
font = font.deriveFont(fontSize);
FontMetrics fm = g2d.getFontMetrics(font);
int textWidth = fm.stringWidth(text);
return textWidth;
}
public static Float pointToFit(double width, String text, Font font, Graphics2D g2d, float min, float max) {
float fontSize = min + ((max - min) / 2f);
font = font.deriveFont(fontSize);
FontMetrics fm = g2d.getFontMetrics(font);
int textWidth = fm.stringWidth(text);
if (fontSize == min || fontSize == max) {
return fontSize;
}
if (textWidth < width) {
return pointToFit(width, text, font, g2d, fontSize, max);
} else if (textWidth > width) {
return pointToFit(width, text, font, g2d, min, fontSize);
}
return fontSize;
}
Important to note, it's not perfect, but it betters a linear progression :P
With this in hand, we can start calculating the required properties we need...
String text = "Happy, Happy, Joy, Joy";
double width = cmToPixel(13.0, 72.0);
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
float fontSize = pointToFit(width, text, font, g2d, 0, (float)width);
font = font.deriveFont(fontSize);
FontMetrics fm = g2d.getFontMetrics(font);
int height = fm.getHeight();
g2d.dispose();
Okay, so this creates a small (1x1) temporary image. We need Graphics context in order to calculate all the other properties. It then calculates the font point size, from it can then calculate the text height
With all that information in hand, we can get around to actually rendering the text...
img = new BufferedImage((int) Math.round(width), height, BufferedImage.TYPE_INT_ARGB);
g2d = img.createGraphics();
g2d.setFont(font);
fm = g2d.getFontMetrics();
g2d.setColor(Color.BLACK);
g2d.drawString(text, 0, fm.getAscent());
g2d.dispose();
Which will eventually output something like this...
I added the red border before I rendered the text so I could see how well it fitted.
Now, this is a really basic example, what this doesn't do is tell you when the text won't fit (ie, the point size is 1 or 0), you'll have to put traps in to catch that yourself
And, because I know you'll probably have lots of fun putting it together, my test code...
import java.awt.Color;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.NumberFormat;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class Test {
public static void main(String[] args) {
try {
System.out.println(new File("Pacifico.ttf").exists());
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
Font font = Font.createFont(Font.TRUETYPE_FONT, new File("Pacifico.ttf"));
String text = "Happy, Happy, Joy, Joy";
double width = cmToPixel(13.0, 72.0);
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
float fontSize = pointToFit(width, text, font, g2d, 0, (float) width);
System.out.println(width);
System.out.println(fontSize);
font = font.deriveFont(fontSize);
FontMetrics fm = g2d.getFontMetrics(font);
int height = fm.getHeight();
g2d.dispose();
img = new BufferedImage((int) Math.round(width), height, BufferedImage.TYPE_INT_ARGB);
g2d = img.createGraphics();
g2d.setColor(Color.RED);
g2d.drawRect(0, 0, img.getWidth() - 1, img.getHeight() - 1);
g2d.setFont(font);
fm = g2d.getFontMetrics();
g2d.setColor(Color.BLACK);
g2d.drawString(text, 0, fm.getAscent());
g2d.dispose();
JOptionPane.showConfirmDialog(null, new ImageIcon(img));
} catch (IOException | FontFormatException e) {
//Handle exception
}
}
public static Float pointToFit(double width, String text, Font font, Graphics2D g2d) {
return pointToFit(width, text, font, g2d, 0f, Float.MAX_VALUE);
}
protected static int widthOfText(String text, Font font, float fontSize, Graphics2D g2d) {
font = font.deriveFont(fontSize);
FontMetrics fm = g2d.getFontMetrics(font);
int textWidth = fm.stringWidth(text);
return textWidth;
}
public static Float pointToFit(double width, String text, Font font, Graphics2D g2d, float min, float max) {
float fontSize = min + ((max - min) / 2f);
NumberFormat nf = NumberFormat.getInstance();
font = font.deriveFont(fontSize);
FontMetrics fm = g2d.getFontMetrics(font);
int textWidth = fm.stringWidth(text);
if (fontSize == min || fontSize == max) {
return fontSize;
}
if (textWidth < width) {
return pointToFit(width, text, font, g2d, fontSize, max);
} else if (textWidth > width) {
return pointToFit(width, text, font, g2d, min, fontSize);
}
return fontSize;
}
public static double cmToPixel(double cm, double dpi) {
return (dpi / 2.54) * cm;
}
}

BufferedImage fill rectangle with transparent pixels

I have a BufferedImage and I am trying to fill a rectangle with transparent pixels. The problem is, instead of replacing the original pixels, the transparent pixels just go on top and do nothing. How can I get rid of the original pixel completely? The code works fine for any other opaque colors.
public static BufferedImage[] slice(BufferedImage img, int slices) {
BufferedImage[] ret = new BufferedImage[slices];
for (int i = 0; i < slices; i++) {
ret[i] = copyImage(img);
Graphics2D g2d = ret[i].createGraphics();
g2d.setColor(new Color(255, 255, 255, 0));
for(int j = i; j < img.getHeight(); j += slices)
g2d.fill(new Rectangle(0, j, img.getWidth(), slices - 1));
g2d.dispose();
}
return ret;
}
public static BufferedImage copyImage(BufferedImage source){
BufferedImage b = new BufferedImage(source.getWidth(), source.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = b.getGraphics();
g.drawImage(source, 0, 0, null);
g.dispose();
return b;
}
Using AlphaComposite, you have at least two options:
Either, use AlphaComposite.CLEAR as suggested, and just fill a rectangle in any color, and the result will be a completely transparent rectangle:
Graphics2D g = ...;
g.setComposite(AlphaComposite.Clear);
g.fillRect(x, y, w, h);
Or, you can use AlphaComposite.SRC, and paint in a transparent (or semi-transparent if you like) color. This will replace whatever color/transparency that is at the destination, and the result will be a rectangle with exactly the color specified:
Graphics2D g = ...;
g.setComposite(AlphaComposite.Src);
g.setColor(new Color(0x00000000, true);
g.fillRect(x, y, w, h);
The first approach is probably faster and easier if you want to just erase what is at the destination. The second is more flexible, as it allows replacing areas with semi-transparency or even gradients or other images.
PS: (As Josh says in the linked answer) Don't forget to reset the composite after you're done, to the default AlphaComposite.SrcOver, if you plan to do more painting using the same Graphics2D object.

Inner-Transparent Selection Window in Java using GlassPane

I am trying to achieve the following
http://www.qksnap.com/i/3hunq/4ld0v/screenshot.png
I am currently able to draw rectangles successfully on a semi-transparent glasspane background using the following code:
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g.setColor(Color.black); // black background
g.fillRect(0, 0, frame.getWidth(), frame.getHeight());
g2.setColor(Color.GREEN.darker());
if (getRect() != null && isDrawing()) {
g2.draw(getRect()); // draw our rectangle (simple Rectangle class)
}
g2.dispose();
}
Which works great, however, I would love to have the area within the rectangle be completely transparent while the outside was still darken much like the screenshot above.
Any ideas?
..have the area within the rectangle be completely transparent while the outside was still darken much like the screenshot above.
Create a Rectangle (componentRect) that is the size of the component being painted.
Create an Area (componentArea) of that shape (new Area(componentRect)).
Create an Area (selectionArea) of the selectionRectangle.
Call componentArea.subtract(selectionArea) to remove the selected part.
Call Graphics.setClip(componentArea)
Paint the semi-transparent color.
(Clear the clipping area if more paint operations are required).
As Andrew has suggested (just beat me while I was finishing off my example)
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g.setColor(Color.black); // black background
Area area = new Area();
// This is the area that will filled...
area.add(new Area(new Rectangle2D.Float(0, 0, getWidth(), getHeight())));
g2.setColor(Color.GREEN.darker());
int width = getWidth() - 1;
int height = getHeight() - 1;
int openWidth = 200;
int openHeight = 200;
int x = (width - openWidth) / 2;
int y = (height - openHeight) / 2;
// This is the area that will be uneffected
area.subtract(new Area(new Rectangle2D.Float(x, y, openWidth, openHeight)));
// Set up a AlphaComposite
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
g2.fill(area);
g2.dispose();
}

Java (AWT): fitting text in a box

I have an application that extends a Frame. Then, it'll display a few lines of text using:
Font f = new Font("Arial", Font.PLAIN, 10);
g.setFont(f);
g.drawString("Test|great Yes ^.", x, y + 10);
Now what happens is that the text doesn't fit in the box around. E.g. I'm expecting the text to fit in [x,y]-[x+width, y+10] (don't care about the width) but it falls somewhat below the y+10 line. Now for most characters ('T', 'e', etc.) this fits but '|' and 'g' don't! They go below the y+10-line. It seems you can't use: draw at y + characterHeight. But what does work?
To see what I mean, here's some sample code:
import java.awt.*;
public class test extends Frame
{
public test()
{
/* retrieve max window size */
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
GraphicsConfiguration [] gc = gs[0].getConfigurations();
Rectangle r = gc[0].getBounds();
setSize(r.width, r.height);
setVisible(true);
}
public void paint(Graphics g)
{
final int windowWidth = getSize().width;
final int windowHeight = getSize().height;
g.setColor(Color.BLUE);
g.fillRect(0, 0, windowWidth, windowHeight);
g.setColor(Color.WHITE);
g.fillRect(0, 100, windowWidth, 110);
int textHeight = 100;
Font f = new Font("Arial", Font.PLAIN, textHeight);
g.setFont(f);
g.setColor(Color.BLACK);
g.drawString("Test|great Yes ^.", 10, 100 + textHeight);
}
public void guiLoop()
{
for(;;) { try { Thread.sleep(1000); } catch(Exception e) { } }
}
public static void main(String [] args)
{
new test().guiLoop();
}
}
I tried the following code as well:
public void paint(Graphics g)
{
final int windowWidth = getSize().width;
final int windowHeight = getSize().height;
g.setColor(Color.BLUE);
g.fillRect(0, 0, windowWidth, windowHeight);
g.setColor(Color.WHITE);
g.fillRect(0, 100, windowWidth, 110);
int textHeight = 100;
String str = "Test|great Yes ^.";
Font f = new Font("Arial", Font.PLAIN, textHeight);
Rectangle2D boundingRectangle = f.getStringBounds(str, 0, str.length(), new FontRenderContext(null, false, false));
f = f.deriveFont((float)(textHeight * (textHeight / boundingRectangle.getHeight())));
boundingRectangle = f.getStringBounds(str, 0, str.length(), new FontRenderContext(null, false, false));
g.drawString(str, 10, 100 + (int)boundingRectangle.getHeight());
g.setFont(f);
g.setColor(Color.BLACK);
g.drawString(str, 10, 100 + textHeight);
}
This is somewhat better: the text is smaller so it might fit, but there's still the problem that the y-position is incorrect.
All help is appreciated!
What about using FontMetrics? You can obtain it from Graphics object with g.getFontMetrics().
Than you can retrieve max descent or ascent or directly height (using getHeight), so your implementation will be font-indipendent and it should work fine.. check documentation here!
EDIT (to explain comments):
there is no a direct way to tell to a string to draw itself in a manner that can fit a box. You have to do it by yourself.. like start from a max font size and check if width fits the box, otherwise decrement size and try again. For height you should FIRST decide (or obtain) max font height, then you can set how many pixel should the box be.
I think I solved it somewhat:
boundingBoxHeight: height of box in which the text should fit
yOffset where to start drawing the font
Font f = new Font("Arial", Font.PLAIN, boundingBoxHeight);
g.setFont(f);
FontMetrics fm = g.getFontMetrics();
double shrink = ((double)textHeight / (double)fm.getHeight());
double newSize = (double)textHeight * shrink;
double newAsc = (double)fm.getAscent() * shrink;
int yOffset = (int)newAsc - fm.getLeading();
f = f.deriveFont((float)newSize);
g.setFont(f);
g.drawString(str, 10, 100 + yOffset);
There's quite a bit of whitespace above the text though.

Categories