標籤:ogr width math 初始化 com 技術分享 實現 graph click
基於
Visual Studio 2012
.net framework 4.5
效果:
代碼:
https://download.csdn.net/download/talkwah/10482880
代碼預覽:
using System;using System.Drawing;using System.Windows.Forms;namespace WFA畫圖{ public partial class Form1 : Form { #region 成員變數 Point m_p1, m_p2; bool m_flgKeuDowm = false; Bitmap m_mapStart; Bitmap m_mapEnd; Bitmap m_mapInit; Graphics m_graphics; #endregion public Form1() { InitializeComponent(); m_graphics = pictureBox1.CreateGraphics(); // 最初的背景圖存起來,清除繪製圖形時用 m_mapInit = (Bitmap)pictureBox1.BackgroundImage; } #region 滑鼠事件 /// <summary> /// 滑鼠按下 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { m_flgKeuDowm = true; _initPoint(e); } /// <summary> /// 滑鼠移動 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { if (!m_flgKeuDowm) { return; } else { m_p2 = new Point(e.X, e.Y); } int width = Math.Abs(e.X - m_p1.X); int height = Math.Abs(e.Y - m_p1.Y); _draw(); } /// <summary> /// 滑鼠抬起 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void pictureBox1_MouseUp(object sender, MouseEventArgs e) { m_flgKeuDowm = false; // 最終的圖片設為背景圖 pictureBox1.BackgroundImage = m_mapEnd; // 起止點初始化 _initPoint(e); } #endregion private void _draw(){ // 每次的【終止圖】都是取自【起始圖】 m_mapEnd = (Bitmap)m_mapStart.Clone(); Graphics g = Graphics.FromImage(m_mapEnd); Pen pen = new Pen(Color.Red,3); if (rdoRect.Checked) { Point p1,p2; _swapPoint(out p1,out p2 ); int width = Math.Abs(p2.X - p1.X); int height = Math.Abs(p2.Y - p1.Y); g.DrawRectangle(pen, p1.X, p1.Y, width, height); }else if(rdoLine.Checked){ // 畫直線不用轉換點座標,直接用成員變數的Point g.DrawLine(pen, m_p1, m_p2); } m_graphics.DrawImage(m_mapEnd, new Point(0, 0)); } private void _initPoint(MouseEventArgs e) { m_p1 = new Point(e.X, e.Y); m_p2 = m_p1; if (pictureBox1.BackgroundImage != null) { m_mapStart = (Bitmap)pictureBox1.BackgroundImage; } } private void _printPoint(Point p) { Console.WriteLine(p.X+","+p.Y); } private void _swapPoint(out Point _p1, out Point _p2) { //實現畫框隨意翻轉 _p1 = m_p1; _p2 = m_p2; if (m_p1.X > m_p2.X) { int tmp = _p1.X; _p1.X = _p2.X; _p2.X = tmp; } if (m_p1.Y > m_p2.Y) { int tmp = _p1.Y; _p1.Y = _p2.Y; _p2.Y = tmp; } } #region 按鈕 private void btnClear_Click(object sender, EventArgs e) { pictureBox1.BackgroundImage = m_mapInit; } private void btnSave_Click(object sender, EventArgs e) { // 儲存 SaveFileDialog dlg = new SaveFileDialog(); dlg.DefaultExt = "png"; dlg.Filter = "Png Files|*.png"; dlg.FileName = ""; DialogResult dlgRet = dlg.ShowDialog(); if (dlgRet == DialogResult.OK) { pictureBox1.BackgroundImage.Save(dlg.FileName, System.Drawing.Imaging.ImageFormat.Png); } } #endregion }}
C#繪圖:帶背景,拖滑鼠畫矩形和直線