C#通过不同按钮在picturebox上画出圆、三角形
可以在定义一个form 的成员来表示要画什么形状,比如一个整数叫 iSharp, 约定0是没有,1是圆2是方什么的。
在按扭click时,按不同的按钮的功能来更新这个iSharp的值,更新为1,2,删除按钮被按就更新为0. 然后,调用picturebox的Invalidate方法,这个方法会引起picturebox重绘。
最后,重写PictureBox的OnPaint方法,或是响应Paint事件,根据iShaper的值来绘出不同的图形。
以下是有保存功能的代码。就是不直接画在picturebox上,而是画在一个Bitmap上,然后把bitmap画到界面上。保存时,只要保存这个bitmap就行了。
publicpartialclassForm2:Form{
//......
privateintiSharp=0;
privateBitmapbmp=null;
privatevoidpictureBox1_Paint(objectsender,PaintEventArgse)
{
bmp=newBitmap(this.pictureBox1.Width,this.pictureBox1.Height,e.Graphics);
varg=Graphics.FromImage(bmp);
g.Clear(Color.White);
switch(this.iSharp)
{
case0:
break;
case1:
g.DrawEllipse(Pens.Black,
newRectangle(1,1,
this.pictureBox1.Width-2,
this.pictureBox1.Height-2));
break;
case2:
g.DrawRectangle(Pens.Blue,
newRectangle(1,1,
this.pictureBox1.Width-2,
this.pictureBox1.Height-2));
break;
case3:
g.DrawPolygon(Pens.DarkGreen,
newPoint[]{
newPoint(1,this.pictureBox1.Height-1),
newPoint(this.pictureBox1.Width-1,this.pictureBox1.Height-1),
newPoint(this.pictureBox1.Width/2,1),
});
break;
default:
g.DrawString("不支持",
newFont("宋体",10.0f),
Brushes.Red,0,0,
StringFormat.GenericDefault);
break;
}
e.Graphics.DrawImage(bmp,0,0);
}
privatevoidbtnCircle_Click(objectsender,EventArgse)
{
this.iSharp=1;
this.pictureBox1.Invalidate();
}
privatevoidbtnDelete_Click(objectsender,EventArgse)
{
this.iSharp=0;
this.pictureBox1.Invalidate();
}
privatevoidbtnRect_Click(objectsender,EventArgse)
{
this.iSharp=2;
this.pictureBox1.Invalidate();
}
privatevoidbtnTran_Click(objectsender,EventArgse)
{
this.iSharp=3;
this.pictureBox1.Invalidate();
}
privatevoidbtnSave_Click(objectsender,EventArgse)
{
bmp.Save("c:\\1.jpg",ImageFormat.Jpeg);
}
}
多重随机标签