Step By Step(Java 2D图形篇<三>) (四)

2014-11-24 03:21:36 · 作者: · 浏览: 1
int w = dmodes[i].getWidth();

8 int h = dmodes[i].getHeight();

9 int depth = dmodes[i].getBitDepth();

10 int refreshRate = dmodes[i].getRefreshRate();

11 System.out.printf("ScreenWidth = %d\t ScreenHeight = %d\t " +

12 "BitDepth = %d\t RefreshRate = %d\n",w,h,depth,refreshRate);

13 }

14 DisplayMode currentDMode = gs.getDisplayMode();

15 int w = currentDMode.getWidth();

16 int h = currentDMode.getHeight();

17 int depth = currentDMode.getBitDepth();

18 int refreshRate = currentDMode.getRefreshRate();

19 System.out.println("The current Display Modes is ");

20 System.out.printf("ScreenWidth = %d\t ScreenHeight = %d\t " +

21 "BitDepth = %d\t RefreshRate = %d\n",w,h,depth,refreshRate);

22 }

23 }

5) 通过图形配置工具类创建和当前图形设备类型兼容的BufferedImage。

这里需要说明一下,每个图形设备都会有一组和当前设备相关的图形配置信息,如分辨率、位深度和色彩类型等。不同的设备之间其图形配置可能存在较大的差异,如屏幕和打印机。那么创建和设备兼容的BufferedImage的目的和应用是什么呢?目的很简单就是为了提高渲染效率。比如当前的BufferedImage对象需要被渲染到JPanel上面,如果该BufferedImage对象的图形配置信息和显示JPanel的屏幕的配置信息相一致,那么在Graphics渲染时,就可以避免因大量的数据转义而带来的额外开销。这种技巧一个非常典型的应用就是Swing的双缓冲技术。由于本篇并不是介绍Swing的专题,而双缓冲又是一个非常通用的技术,这里就不再给出更多的解释了。

下面的示例代码将给出一个用于创建与设备兼容的BufferedImage对象的工具类。

1 class CompatibleImageUtil {

2 private static GraphicsConfiguration gc;

3 public static GraphicsConfiguration getConfiguration() {

4 if (gc == null) {

5 // 1. 获取本地当前正在使用的图形环境

6 GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();

7 // 2. 获取当前环境正在使用的图形设备

8 GraphicsDevice gs = ge.getDefaultScreenDevice();

9 // 3. 获取当前设备正在使用的图形配置。

10 gc = gs.getDefaultConfiguration();

11 }

12 return gc;

13 }

14 //基于参数srcImage的宽度、高度和透明度参数来创建一个和设备兼容的BufferedImage对象

15 public static BufferedImage createCompatibleImage(BufferedImage srcImage) {

16 return createCompatibleImage(srcImage, srcImage.getWidth(), srcImage.getHeight());

17 }

18 public static BufferedImage createCompatibleImage(BufferedImage srcImage, int width, int height) {

19 return getConfiguration().createCompatibleImage(width, height, srcImage.getTransparency());

20 }

21 public static BufferedImage createCompatibleImage(int width, int height) {

22 return getConfiguration().createCompatibleImage(width, height);

23 }

24 public static BufferedImage createCompatibleTranslucentImage(int width, int height) {

25 return getConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);

26 }

27 //加载原图像,在基于加载后源图像的宽度、高度和透明度创建一个和设备兼容的BufferedImage对象

28 public static BufferedImage loadCompatibleImage(File filename) throws IOException {

29 BufferedImage image = ImageIO.read(filename);

30 return toCompatibleImage(image);

31 }

32 public static BufferedImage toCompatibleImage(BufferedImage image) {

33