Graphics2D绘制图形

1.文字压缩显示
参照java自带的demo下的jfc/java2d的ColorConvert,做了简单的修改。文字压缩显示的思路是将图片的宽度设为期望的宽度即可
public class ColorConvert extends JPanel {

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Dimension d = getSize();
render(d.width, d.height / 2, (Graphics2D) g);
}

public void render(int w, int h, Graphics2D g2) {
BufferedImage srcImg =
new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D imageG2 = srcImg.createGraphics();

//设置白底黑字
imageG2.setBackground(Color.WHITE);
imageG2.clearRect(0, 0, w, h);
imageG2.setColor(Color.BLACK);

String text = "标题:订货单位";
Font font = new Font("宋体", Font.BOLD, 28);
FontRenderContext frc = g2.getFontRenderContext();
TextLayout tl = new TextLayout(text, font, frc);
tl.draw(imageG2, 50, 50);

//文字的宽度将压缩一半显示
g2.drawImage(srcImg, 0, 0, srcImg.getWidth()/2, srcImg.getHeight(), null);
//文字正常显示
g2.drawImage(srcImg, 0, srcImg.getHeight(), srcImg.getWidth(), srcImg.getHeight(), null);
}


public static void main(String s[]) {
JFrame f = new JFrame();
f.setSize(400, 500);
f.getContentPane().add(new ColorConvert());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}


2.空心字
public class TestPanel extends JPanel {

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
tt(g);
}

private void tt(Graphics g) {
Graphics2D g2 = (Graphics2D)g;

java.awt.font.FontRenderContext frc = g2.getFontRenderContext();
java.awt.Font f = new java.awt.Font("宋体", java.awt.Font.PLAIN, 80);
java.awt.font.TextLayout tl = new java.awt.font.TextLayout("i序号_i", f, frc);
AffineTransform translateInstance = AffineTransform.getTranslateInstance(1, 200);
java.awt.Shape sha = tl.getOutline(translateInstance);
g2.setColor(java.awt.Color.BLUE);
g2.draw(sha);
//g2.fill(sha);//如果去掉这行就是空心字了
}

public static void main(String[] args) {
JFrame f = new JFrame();
f.getContentPane().add(new TestPanel());
f.setSize(400, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}

你可能感兴趣的:(java2d)