Posted on 2012-07-10 13:09
小胡子 阅读(3653)
评论(1) 编辑 收藏
最近在给客户做项目的时候客户提出要求要给图片加水印, 在添加文字水印时,让用户自定义自体,当用户在选择字体时,如果勾选了删除线和下划线选项,而java.awt.Font不支持下划线和删除线的style, 这怎么办呢?
还好,Java提供了 AttributedString 类, 通过
attributedString.addAttribute(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
attributedString.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
即可给文字添加删除线和下划线,再通过
graphics2D.drawString(as.getIterator(), x, y);
就可以显示下划线和删除线的效果了。
- import java.awt.Font;
- import java.awt.Graphics;
- import java.awt.Graphics2D;
- import java.awt.RenderingHints;
- import java.awt.font.TextAttribute;
- import java.text.AttributedString;
-
- import javax.swing.JFrame;
- import javax.swing.JPanel;
-
- public class IteratorUnderStrike extends JPanel{
- public void paint(Graphics g) {
- Graphics2D g2 = (Graphics2D) g;
-
- String s = "/"www.java2s.com/" is great.";
-
- g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
- RenderingHints.VALUE_ANTIALIAS_ON);
- Font plainFont = new Font("Times New Roman", Font.PLAIN, 24);
-
- AttributedString as = new AttributedString(s);
- as.addAttribute(TextAttribute.FONT, plainFont);
- as.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON, 1, 15);
- as.addAttribute(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON, 18, 25);
-
- g2.drawString(as.getIterator(), 24, 70);
- }
-
- public static void main(String[] args) {
- JFrame f = new JFrame();
- f.getContentPane().add(new IteratorUnderStrike());
- f.setSize(850, 250);
- f.show();
- }
- }
http://yanghuidang.iteye.com/blog/1203582