做一個簡單的繪圖程序?
實現過程:
(1) 新建窗體應用程序
(2) 添加一個MenuScrip控件;添加一個ToolScrip控件。
在ToolScrip控件中對每個單元,要將DisplayStyle屬性改為Text
(3)程序代碼。
1、新建菜單事件主要用白色清除窗體的背景,從而實現“文件新建”功能
[csharp]
private void 新建ToolStripMenuItem_Click(object sender, EventArgs e)
{
Graphics g = this.CreateGraphics();
g.Clear(backColor);
toolStrip1.Enabled = true;
//創建一個Bitmap
theImage = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height);
editFileName = "新建文件";
//修改窗口標題
this.Text = "MyDraw\t" + editFileName;
ig = Graphics.FromImage(theImage);
ig.Clear(backColor);
}
2、打開事件用于打開“打開文件”對話框,并選擇相應的圖片,將圖片繪制到窗體上.
[csharp]
private void 打開ToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.Multiselect = false;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//修改窗口標題
this.Text = "MyDraw\t" + openFileDialog1.FileName;
editFileName = openFileDialog1.FileName;
theImage = Image.FromFile(openFileDialog1.FileName);
Graphics g = this.CreateGraphics();
g.DrawImage(theImage, this.ClientRectangle);
ig = Graphics.FromImage(theImage);
ig.DrawImage(theImage, this.ClientRectangle);
//ToolBar可以使用了
toolStrip1.Enabled = true;
}
}
(3) 保存菜單項的Click事件用于將窗體背景保存為bmp格式的圖片
[csharp]
private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
{
saveFileDialog1.Filter = "圖像(*.bmp)|*.bmp";
saveFileDialog1.FileName = editFileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
theImage.Save(saveFileDialog1.FileName, ImageFormat.Bmp);
this.Text = "MyDraw\t" + saveFileDialog1.FileName;
editFileName = saveFileDialog1.FileName;
}
}
(4) 在Paint事件中將Image中保存的圖像,繪制出來
[csharp]
private void Form1_Paint(object sender, PaintEventArgs e)
{
//將Image中保存的圖像,繪制出來
Graphics g = this.CreateGraphics();
if (theImage != null)
{
g.Clear(Color.White);
g.DrawImage(theImage, this.ClientRectangle);
}
}
(5)添加Frm_Text.cs文字輸入框。
添加一個Window窗體,取名為Frm_Text,然后對窗體的屬性修改:
把FormBorderStyle屬性改為 None;
把Modifiers的屬性改為 Public
(6) 在窗體的MouseDown事件中,如果當前繪制的是字符串,在鼠標的當前位置顯示文本框;如果繪制的是圖開,設置圖形的起始位置。
[cpp]
private void Frm_Main_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
//如果選擇文字輸入,則打開strInput窗體
if (drawTool == drawTools.String)
{
Frm_Text inputBox = new Frm_Text();
inputBox.StartPosition = FormStartPosition.CenterParent;
if (inputBox.ShowDialog() == DialogResult.OK)
{
Graphics g = this.CreateGraphics();
Font theFont = this.Font;
g.DrawString(inputBox.textBox1.Text, theFont, new SolidBrush(foreColor), e.X, e.Y);
ig.DrawString(inputBox.textBox1.Text, theFont, new SolidBrush(foreColor), e.X, e.Y);
}
}
//如果開始繪制,則開始記錄鼠標位置
else if ((isDrawing = !isDrawing) == true)
{
startPoint = new Point(e.X, e.Y);
oldPoint = new Point(e.X, e.Y);
}
}
}