在 PictureBox
控件上显示图片时,通过鼠标移动获取其在图片中的坐标,并将相关信息显示在 label
中。
转载:pictureBox sizemode=zoom时图片像素坐标-优快云博客
在pictureBox控件中绑定MouseMove事件
if(this.pictureBox1.Image != null)// MouseMove事件中涉及对图片与控件之间的计算关系,所以先检查图片是否存在
{
// 得到本Form类中pictureBox1中所显示图片的宽和高,单位为像素
int originalWidth = this.pictureBox1.Image.Width;
int originalHeight = this.pictureBox1.Image.Height;
// 通过反射机制获取 PictureBox 控件中图片的实际显示区域(即 ImageRectangle 属性)
PropertyInfo rectangleProperty = this.pictureBox1.GetType().GetProperty("ImageRectangle", BindingFlags.Instance | BindingFlags.NonPublic);
Rectangle rectangle = (Rectangle)rectangleProperty.GetValue(this.pictureBox1, null);
// 图片在PictureBox控件中的实际(缩放后)显示区域(包括显示的X和Y坐标,以及Width和Height)
int currentWidth = rectangle.Width;
int currentHeight = rectangle.Height;
// 计算缩放比例
double rate = (double)currentHeight / (double)originalHeight;
// 计算上下左右的留白宽度(zoom模式下,上下有相同留白,左右有相同留白)
int black_left_width = (currentWidth == this.pictureBox1.Width) ? 0 : (this.pictureBox1.Width - currentWidth) / 2;
int black_top_height = (currentHeight == this.pictureBox1.Height) ? 0 : (this.pictureBox1.Height - currentHeight) / 2;
// 缩放图中的鼠标坐标
int zoom_x = e.X - black_left_width;
int zoom_y = e.Y - black_top_height;
// 原始图中鼠标坐标
double original_x = (double)zoom_x / rate;
double original_y = (double)zoom_y / rate;
// 使用 StringBuilder 构建一段字符串,依次记录以下信息
StringBuilder sb = new StringBuilder();
sb.AppendFormat("原始尺寸{0}/{1}(宽/高)\r\n", originalWidth, originalHeight);
sb.AppendFormat("缩放状态图片尺寸{0}/{1}(宽/高)\r\n", currentWidth, currentHeight);
sb.AppendFormat("缩放比率{0}\r\n", rate);
sb.AppendFormat("左留白宽度{0}\r\n", black_left_width);
sb.AppendFormat("上留白高度{0}\r\n", black_top_height);
sb.AppendFormat("当前鼠标坐标{0}/{1}(X/Y)\r\n", e.X, e.Y);
sb.AppendFormat("缩放图中鼠标坐标{0}/{1}(X/Y)\r\n", zoom_x, zoom_y);
sb.AppendFormat("原始图中鼠标坐标{0}/{1}(X/Y)\r\n", original_x, original_y);
this.label1.Text = sb.ToString();
}
else
{
//MessageBox.Show("没有加载图片,无法获取尺寸!");
return;
}
自我总结点滴,欢迎批评指正。