Graphics2D字体增加阴影
时间: 2023-08-02 19:11:28 浏览: 92
要在Java的Graphics2D中添加文本阴影,可以使用Java的TextLayout和TextAttribute实现。下面是一个示例代码:
```
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;
import java.text.AttributedString;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ShadowedText extends JPanel {
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
String text = "Hello, World!";
Font font = new Font("Arial", Font.BOLD, 48);
AttributedString attString = new AttributedString(text);
attString.addAttribute(TextAttribute.FONT, font);
TextLayout textLayout = new TextLayout(attString.getIterator(), g2d.getFontRenderContext());
Rectangle2D bounds = textLayout.getBounds();
g2d.setColor(Color.BLACK);
textLayout.draw(g2d, 50, 50);
g2d.setColor(Color.WHITE);
textLayout.draw(g2d, 50 + 2, 50 + 2);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Shadowed Text");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new ShadowedText());
frame.setSize(400, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
```
在上面的示例代码中,我们首先创建一个AttributedString对象,然后使用TextAttribute将其与指定的字体相关联。接下来,我们使用TextLayout类计算文本的边界框并在屏幕上绘制文本。最后,我们使用相同的TextLayout对象和偏移量再次绘制文本,但这次我们使用白色表示文本的阴影,并在偏移量上添加了2个像素。这样就可以在文本周围创建一个黑色的阴影效果。