java graphics绘图 drawString文字发光 代码
时间: 2023-07-09 22:36:53 浏览: 90
发光的文字
要让文字发光,可以使用 Java Graphics2D 的阴影效果来实现。以下是一个示例代码:
```java
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TextGlowExample extends JPanel {
private static final long serialVersionUID = 1L;
private String text = "Hello, World!";
private Font font = new Font("Arial", Font.BOLD, 50);
private Color color = Color.YELLOW;
private int glowSize = 10;
public TextGlowExample() {
setPreferredSize(getPreferredSize());
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// 设置字体和颜色
g2d.setFont(font);
g2d.setColor(color);
// 计算文字的大小和位置
TextLayout textLayout = new TextLayout(text, font, g2d.getFontRenderContext());
Rectangle2D bounds = textLayout.getBounds();
int x = getWidth() / 2 - (int) bounds.getWidth() / 2;
int y = getHeight() / 2 + (int) bounds.getHeight() / 2;
// 开启抗锯齿和阴影效果
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
// 绘制文字的阴影
g2d.setColor(Color.WHITE);
for (int i = 0; i < glowSize; i++) {
g2d.setStroke(new java.awt.BasicStroke((float) (glowSize - i)));
textLayout.draw(g2d, x, y + i);
}
// 绘制文字
g2d.setColor(color);
g2d.setStroke(new java.awt.BasicStroke(1f));
textLayout.draw(g2d, x, y);
}
@Override
public java.awt.Dimension getPreferredSize() {
return new java.awt.Dimension(300, 200);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Text Glow Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TextGlowExample());
frame.pack();
frame.setVisible(true);
}
}
```
在上面的代码中,我们使用了 `TextLayout` 类来计算文字的大小和位置,并使用了 `RenderingHints` 来开启抗锯齿和阴影效果。在绘制文字时,我们首先绘制了文字的阴影,然后再绘制文字本身,从而实现了发光的效果。
阅读全文