1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
|
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.swing.JFrame;
import javax.imageio.ImageIO;
import ci.util.graphic.UtilGraphic;
public class Test {
public static void main(String[] args) {
FontRenderContext frc = new FontRenderContext(null, false, false);
Font font = new Font("Serif", Font.PLAIN, 24);
char[] tc = {'f', 'g', '@', '£'};
Rectangle2D bounds;
double ascent;
double descent;
BufferedImage img = new BufferedImage(500, 600, BufferedImage.TYPE_INT_RGB);
img.createGraphics();
Graphics2D g = (Graphics2D)img.getGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
int xPos = 10;
int yPos = 50;
int curr_pos=xPos;
for(int i=0 ; i< 4 ; i++)
{
TextLayout layout = new TextLayout(""+tc[i], font, frc);
bounds = layout.getBounds();
ascent = -bounds.getY();
descent = bounds.getHeight()+bounds.getY();
stretchingCapacity = 0;
String tcS = Character.toString(tc[i]);
// get metrics from the graphics
FontMetrics metrics = g.getFontMetrics(font);
// get the height of a line of text in this font and render context
int hgt = metrics.getHeight();
// get the advance of my text in this font and render context
int adv = metrics.stringWidth(tcS);
// calculate the size of a box to hold the text with some padding.
Dimension size = new Dimension(adv+2, hgt+2);
GlyphVector gv = font.createGlyphVector(frc, tcS);
Rectangle2D r2 = gv.getVisualBounds();
g.drawGlyphVector(gv,(float)curr_pos ,yPos);
int fixedSpace = 5;
curr_pos+= size.width + fixedSpace;
}
render(img,500, 500);
}
public static void render (BufferedImage img, int sizeW, int sizeH) {
JFrame frame = new JFrame("Image Maker");
frame.setBounds(0, 0, sizeW, sizeH);
JImagePanel panel = new JImagePanel(img, 0, 0);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
} |
Partager