一、创建画图板
GDI+用于创建各种图形,能实现大部分Windows操作系统中自带的画图板功能。Windows自带的画图板是一个经典的画图工具,这个工具的特点是简单实用。在C#中实现画图板的基本功能需要一些基本的GDI+类和方法,包括画直线DrawLine、画矩形DrawRectangle及其他功能。还需要如设置颜色之类的功能,需要使用Color枚举。
画图板中最基本的功能为画直线,使用SplitControl控件和按钮控件,窗体左下角添加控件用于选择颜色:
颜色选择按钮的单击事件代码如下:
private void button2_Click(object sender,EventArgs e)
{
color=Color.Black;
}
private void button3_Click(object sender,EventArgs e)
{
color=Color.Yellow;
}
private void button4_Click(object sender,EventArgs e)
{
color=Color.Red;
}
private void button5_Click(object sender,EventArgs e)
{
color=Color.Blue;
}
编写Panel2控件的MouseDown和MouseUp事件代码如下:
private void splitContainer1_panel2_MouseDown(object sender,MouseEventArgs e)
{
if(e.Button == MouseButtons.Left)
{
p1.X=e.X;
p1.Y=e.Y;
}
}
private void splitContainer1_panel2_MouseUp(object sender,MouseEventArgs e)
{
if(e.Button==MouseButton.Left)
{
p2.X=e.X;
p2.Y=e.Y;
g=splitContainer1.panel2.CreateGraphics();
g.DrawLine(new Pen(color),p1,p2);
}
程序中需要声明的变量如下:
private Point p1=new Point();
private Point p2=new Point();
Graphics g;
Color color=Color.Black;
}
二、画矩形
public partial class Form1:Form
{
//声明用于绘图的两个点
private Point p1=new Point();
private Point p2=new Point();
//声明用于绘图的对象和颜色变量
Graphics g;
Color color =Color.Black;
//自定义的变量,用于记录当前选择的图形
Style style=Style.Line;
///<summary>
///图形枚举
///</summary>
enum Style
{
///<summary>
///直线
///</summary>
Line,
///<summary>
///矩形
///</summary>
Rect
}
public Form1()
{
InitializeComponent();
}
private void splitContainer1_Panel2_MouseDown(object sender,MouseEventArgs e)
{
//鼠标按下的时候记录坐标
if(e.Button == MouseButtons.Left)
{
p1.X=e.X;
p1.Y=e.Y;
}
}
private void splitContainer1_panel2_MouseUp(object sender,MouseEventArgs e)
{
//鼠标抬起的时候记录坐标
if(e.Button == MouseButtons.Left)
{
p2.X=e.X;
p2.Y=e.Y;
g=splitContainer1.Panel2.CreateGraphics();
//判断当前的绘图类型并绘图
switch(style)
{
case Style.Line:
g.DrawLine(new Pen(color),p1,p2);
break;
case Style.Rect:
g.DrawRectangle(new Pen(color),new Rectangle(p1,new Size(Math.Abs(p2.X-p1.X),Math.Abs(p2.Y-p1.Y))));
break;
default:
break;
}
}
}
///<summary>
///黑色
///</summary>
private void button2_Click(object sender,EventArgs e)
{
color=Color.Black;
}
........颜色设置类似
///<summary>
///直线
///</summary>
private void button1_Click(object sender,EventArgs e)
{
style=Style.Line;
}
///<summary>
///矩形
///</summary>
private void button6_Click(object sender,EventArgs e)
{
style=Style.Rect;
}
}
椭圆的话类似的代码:
case Style.Ellipse:
g.DrawEllipse(new Pen(color),new Rectangle(p1,new Size(Math.Abs(p2.X-p1.X),Math.Abs(p2.Y-p1.Y))));
break;