如果仅仅绘制一些简单的几何图形,程序的图形效果依然比较单调 。 AWT 也允许在组件上绘制位图, Graphics 提供了 drawlmage() 方法用于绘制位图,该方法需要一个Image参数一一代表位图,通过该方法就可 以绘制出指定的位图 。
位图使用步骤:
1.创建Image的子类对象BufferedImage(int width,int height,int ImageType),创建时需要指定位图的宽高及类型属性;此时相当于在内存中生成了一张图片;
2.调用BufferedImage对象的getGraphics()方法获取画笔,此时就可以往内存中的这张图片上绘图了,绘图的方法和之前学习的一模一样;
3.调用组件的drawImage()方法,一次性的内存中的图片BufferedImage绘制到特定的组件上。
使用位图绘制组件的好处:
使用位图来绘制组件,相当于实现了图的缓冲区,此时绘图时没有直接把图形绘制到组件上,而是先绘制到内存中的BufferedImage上,等全部绘制完毕,再一次性的图像显示到组件上即可,这样用户的体验会好一些。
案例:
通过BufferedImage实现一个简单的手绘程序:通过鼠标可以在窗口中画图。
演示代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
| import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage;
public class HandDraw { private final int AREA_WIDTH = 500; private final int AREA_HEIGHT = 400; private int preX = -1; private int preY = -1; private PopupMenu colorMenu = new PopupMenu(); private MenuItem redItem = new MenuItem("红色"); private MenuItem greenItem = new MenuItem("绿色"); private MenuItem blueItem = new MenuItem("蓝色"); private BufferedImage image = new BufferedImage(AREA_WIDTH,AREA_HEIGHT,BufferedImage.TYPE_INT_RGB); private Graphics g = image.getGraphics(); private Frame frame = new Frame("简单手绘程序"); private Canvas drawArea = new Canvas(){ public void paint(Graphics g) { g.drawImage(image,0,0,null); } }; private Color forceColor = Color.BLACK; public void init(){ ActionListener menuListener = new ActionListener() { public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); switch (command){ case "红色": forceColor=Color.RED; break; case "绿色": forceColor = Color.GREEN; break; case "蓝色": forceColor = Color.BLUE; break; } } };
redItem.addActionListener(menuListener); greenItem.addActionListener(menuListener); blueItem.addActionListener(menuListener); colorMenu.add(redItem); colorMenu.add(greenItem); colorMenu.add(blueItem); drawArea.add(colorMenu); g.fillRect(0,0,AREA_WIDTH,AREA_HEIGHT); drawArea.setPreferredSize(new Dimension(AREA_WIDTH,AREA_HEIGHT)); drawArea.addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { if (preX>0 && preY>0){ g.setColor(forceColor); g.drawLine(preX,preY,e.getX(),e.getY()); }
preX = e.getX(); preY = e.getY();
drawArea.repaint(); } }); drawArea.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) { boolean popupTrigger = e.isPopupTrigger(); if (popupTrigger){ colorMenu.show(drawArea,e.getX(),e.getY()); } preX = -1; preY = -1;
} }); frame.add(drawArea);
frame.pack(); frame.setVisible(true); } public static void main(String[] args) { new HandDraw().init(); } }
|
如果您有什么问题或建议可以在下方的评论区评论,我会及时回复的。
欢迎关注我的公众号,共同学习,共同提升!
您可以通过公众号向我留言,也可以通过邮箱(lklong@88.com)联系我