浅析C#中图形编程
像Java一样,C#提供了一整套相当丰富的类库、方法以及事件以供开发者使用。C#还引入了GDI+,它是由GDI演变而来的,具有比GDI更强大的功能而且简化了程序员的编程工作。所以开发者运用这些,就可以很方便的开发出具有强大图形图像功能的应用程序了。本文,笔者就通过一些实例像读者介绍一下C#中的图形编程的基本知识。
简单实例:
首先,让我们从例子开始,以下是一个最简单的实例:
using System; |
在上面的实例中,我们用到了一个方法:DrawString(),它带有5个参数。同时,我们发现在运用DrawString()方法以前,我们先创建了一个Graphics类型的对象g=e.Graphics,这就说明了在运用任何图形类的方法以前我们必须先创建该类的一个实例化对象。在DrawString()方法后,我们用到了DrawRectangle()方法,其实我们还可以运用其他的方法来画椭圆或是多边形等等。第一个实例还是相当简单易懂的,不是吗?
变换图形的度量单位:
在图形编程中,默认的图形度量单位是象素。不过,你可以通过修改PageUnit属性来修改图形的度量单位,可以是英寸或是毫米等。实现方法如下:
Graphics g = e.Graphics; |
操作颜色选择对话框:
在实际运用特别是图形图像编程过程中,我们可能会经常碰到颜色选择对话框(以及下面要提到的字体选择对话框)。使用颜色选择对话框,我们可以让用户来选择系统预定的颜色以及用户自定义的颜色。在使用颜色选择对话框之前,我们必须先创建一个ColorDialog类型的对象:
ColorDialog cd = new ColorDialog(); |
然后,我们就可以用ShowDialog()方法来显示颜色选择对话框了。之后,就可以通过调用用户的颜色选择进行相关的图形操作了。
以下,我给大家一个实例。该实例中有一个按钮和一个文本框,通过点击按钮可以调出颜色选择对话框,根据用户的颜色选择就可以设置文本框的背景颜色了。
using System; |