1.效果展示
代码
/// <summary>
/// 记录鼠标移动时的位置
/// </summary>
private Point _mouseLocation;
//鼠标移动事件
private void pic_1_MouseMove(object sender, MouseEventArgs e)
{
_mouseLocation = e.Location;
pic_1.Refresh();
}
//绘图事件
private void pic_1_Paint(object sender, PaintEventArgs e)
{
var pic = (PictureBox)sender;
//定义两个点
var points = new Point[2];
points[0] = new Point(101, 43);
points[1] = new Point(548, 536);
var x1 = points[0].X;
var y1 = points[0].Y;
var x2 = points[1].X;
var y2 = points[1].Y;
//定义两个画笔
var brush = new SolidBrush(Color.FromArgb(127, Color.Black));
var pen = new Pen(Brushes.Brown, 3);
e.Graphics.Clear(Color.SkyBlue);//清除整个绘图面并以指定背景色填充
#region [绘制一张图像]
var bmp = (Bitmap)Image.FromFile(Application.StartupPath + @"\猫咪.jpg", false); //从指定路径获取一张Bitmap
var rectBmpPos = new Rectangle();//获取图像显示的位置和宽、高信息
//取 PictureBox和Bitmap 的宽高比
var picByBmpScale = Math.Min((float)pic.Width / bmp.Width, (float)pic.Height / bmp.Height);
rectBmpPos.Width = (int)(bmp.Width * picByBmpScale);
rectBmpPos.Height = (int)(bmp.Height * picByBmpScale);
rectBmpPos.X = (pic.Width - rectBmpPos.Width) / 2;
rectBmpPos.Y = (pic.Height - rectBmpPos.Height) / 2;
var rectBmpSize = new Rectangle(0, 0, bmp.Width, bmp.Height);//图像显示的区域
e.Graphics.SmoothingMode = SmoothingMode.HighQuality;//指定抗锯齿的呈现
e.Graphics.DrawImage(bmp, rectBmpPos, rectBmpSize, GraphicsUnit.Pixel);//绘制图像
bmp.Dispose();
#endregion [绘制一张图像]
#region [画一条线段,端点处以椭圆代表点]
e.Graphics.FillEllipse(brush, x1 - 3, y1 - 3, 6, 6);//绘制一个椭圆,填充内部颜色,可以代表一个点
e.Graphics.FillEllipse(brush, x2 - 3, y2 - 3, 6, 6);//绘制一个椭圆,填充内部颜色,可以代表一个点
e.Graphics.DrawLine(pen, x1, y1, x2, y2);//绘制一条直线
#endregion [画一条线段,端点处以椭圆代表点]
#region [绘制一个矩形框]
if (x1 > x2)
{
x1 = x1 + x2;
x2 = x1 - x2;
x1 = x1 - x2;
}
if (y1 > y2)
{
y1 = y1 + y2;
y2 = y1 - y2;
y1 = y1 - y2;
}
e.Graphics.DrawRectangle(pen, x1, y1, x2 - x1, y2 - y1);
#endregion [绘制一个矩形框]
#region [当前鼠标所在位置绘制十字交叉线,并输出坐标信息]
e.Graphics.DrawLine(pen, _mouseLocation.X, 0, _mouseLocation.X, pic.Height);//绘制垂直条
e.Graphics.DrawLine(pen, 0, _mouseLocation.Y, pic.Width + 200, _mouseLocation.Y);//绘制水平线条
string strLoc = $"({_mouseLocation.X},{_mouseLocation.Y})";
Font font = new Font("Arial", 12f, FontStyle.Bold);
SizeF selPtStrSize = e.Graphics.MeasureString(strLoc, font);//文字的宽高
var strPoint = _mouseLocation;
if (strPoint.X > pic.Width / 2 && strPoint.Y < pic.Height / 2)//右上角
{
strPoint.X -= (int)selPtStrSize.Width;
}
else if (strPoint.X > pic.Width / 2 && strPoint.Y > pic.Height / 2)//右下角
{
strPoint.X -= (int)selPtStrSize.Width;
strPoint.Y -= (int)selPtStrSize.Height;
}
else if (strPoint.X < pic.Width / 2 && strPoint.Y > pic.Height / 2)//左下角
{
strPoint.Y -= (int)selPtStrSize.Height;
}
e.Graphics.DrawString(strLoc, font, new SolidBrush(Color.Black), strPoint);//绘制文字
#endregion [当前鼠标所在位置绘制十字交叉线,并输出坐标信息]
}