38 boolean antialiasTextOn = rhints
39 .containsValue(RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
40 if (!isOutput)
41 System.out.println("VALUE_TEXT_ANTIALIAS_ON is "
42 + (antialiasTextOn "on." : "off."));
43 // 2. 在第二泳道关闭文字抗锯齿
44 g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
45 RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
46 g2d.drawString("Hello World", 20, getHeight() / 4 + 40);
47 rhints = g2d.getRenderingHints();
48 antialiasTextOn = rhints
49 .containsValue(RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
50 if (!isOutput)
51 System.out.println("VALUE_TEXT_ANTIALIAS_OFF is "
52 + (antialiasTextOn "on." : "off."));
53 isOutput = true;
54 }
55 //打开和关闭图形抗锯齿提示
56 private void paintAntialiasingShape(Graphics g) {
57 Graphics2D g2d = (Graphics2D) g;
58 //将笔划设置更粗,这样对比效果更明显
59 Stroke s = new BasicStroke(2);
60 g2d.setStroke(s);
61 Ellipse2D e1 = new Ellipse2D.Double(20, getHeight()/2 + 20,60,60);
62 //3. 在第三泳道打开图形抗锯齿
63 g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
64 RenderingHints.VALUE_ANTIALIAS_ON);
65 g2d.draw(e1);
66 Ellipse2D e2 = new Ellipse2D.Double(20, getHeight()*3/4 + 20,60,60);
67 //4. 在第四泳道关闭图形抗锯齿
68 g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
69 RenderingHints.VALUE_ANTIALIAS_OFF);
70 g2d.draw(e2);
71 }
72 }
9. 图像的读取器和写入器:
从Java SE6 开始,JDK中提供了对GIF、JPEG、PNG、BMP等文件格式的读写支持。我们可以通过ImageIO.read和ImageIO.write两个静态方法分别读取和写入图形文件。ImageIO会根据文件的类型选择适当的读取器和写入器,而文件的类型主要是通过目标文件的扩展名和文件中的Magic Number来判断的。如果没有找到合适的读取器,ImageIO.read将返回null。
通常而言,我们在进行一些图形操作时,都是基于Java 2D中的BufferedImage类协助完成的,因此我们在读取图形文件时,我们的目标也是将图形文件包含的数据读入BufferedImage对象中,以供后用。
1) 直接读取只是包含一幅图像的数据文件:
1 public class MyTest extends JPanel {
2 private static BufferedImage image = null;
3 public static void main(String[] args) throws IOException {
4 JFrame frame = new JFrame();
5 frame.setTitle("ImageIO Read");
6 frame.setSize(300, 400);
7 frame.addWindowListener(new WindowAdapter() {
8 public void windowClosing(WindowEvent e) {
9 System.exit(0);
10 }
11 });
12 Container contentPane = frame.getContentPane();
13 readByFile();
14 // or readByInputStream();
15 //两种方式可以得到相同的效果,只是由于readByInputStream()在读入的
16 //过程中使用了BufferedInputStream,读取效率可能会更高。
17 contentPane.add(new MyTest());
18 frame.show();
19 }
20 private static void readByFile() throws IOException {
21 File sourceimage = new File("D:/desktop.png");
22 image = (BufferedImage)ImageIO.read(sourceimage);
23 }
24 private static