该方法
drawString()使用x和y作为最左边字符的基线。数字通常没有后代;如果true相同,则
text在位置(0,0)绘制的字符串将完全在图像外部呈现。请参阅此示例。
附录:你可能会遇到图像中的颜色模型不兼容的问题。一种简单的方法是渲染图像,然后在原位对其进行修改。
import java.awt.Color;import java.awt.Dimension;import java.awt.EventQueue;import java.awt.Font;import java.awt.FontMetrics;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.image.BufferedImage;import java.io.IOException;import java.net.URL;import javax.imageio.ImageIO;import javax.swing.Jframe;import javax.swing.JPanel;public class TextOverlay extends JPanel { private BufferedImage image; public TextOverlay() { try { image = ImageIO.read(new URL( "http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png")); } catch (IOException e) { e.printStackTrace(); } image = process(image); } @Override public Dimension getPreferredSize() { return new Dimension(image.getWidth(), image.getHeight()); } private BufferedImage process(BufferedImage old) { int w = old.getWidth() / 3; int h = old.getHeight() / 3; BufferedImage img = new BufferedImage( w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); g2d.drawImage(old, 0, 0, w, h, this); g2d.setPaint(Color.red); g2d.setFont(new Font("Serif", Font.BOLD, 20)); String s = "Hello, world!"; FontMetrics fm = g2d.getFontMetrics(); int x = img.getWidth() - fm.stringWidth(s) - 5; int y = fm.getHeight(); g2d.drawString(s, x, y); g2d.dispose(); return img; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image, 0, 0, null); } private static void create() { Jframe f = new Jframe(); f.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); f.add(new TextOverlay()); f.pack(); f.setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { create(); } }); }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)