C# 编写点击图片框计算出在文件中的像素点
2016-05-26 00:00
483 查看
OK,今天的教程我们需要做的是在图片框中显示一张图片,然后我们点击图片上任意位置,计算出在该图片实际点击为的位置。
如我选择720 * 1280的图片,而图片框的大小为 360 *640,那么要怎样计算出位置呢。
OK,那么开始.
首先需要添加一个图片框,之后我们需要给该图片框添加一个鼠标,该鼠标事件是为了对点击位置进行处理。
首先需要做的是将图片显示到图片框中,由于需要释放资源,这里不直接显示,而是通过IO接口实现,异常直接使用Exception
显示图片成功之后,我们需要获取照片的宽度和高度,也就是像素大小
准备工作都做好了.那么就需要处理图片框的鼠标事件了
一般为了稳定,都将图片框的大小固定.小伙伴们可以试下哈~~~
如我选择720 * 1280的图片,而图片框的大小为 360 *640,那么要怎样计算出位置呢。
OK,那么开始.
首先需要添加一个图片框,之后我们需要给该图片框添加一个鼠标,该鼠标事件是为了对点击位置进行处理。
首先需要做的是将图片显示到图片框中,由于需要释放资源,这里不直接显示,而是通过IO接口实现,异常直接使用Exception
int imageWidth = 0; int imgaeHeight = 0; String imageFilePath = ""; System.IO.FileStream fs = null; try { fs = new System.IO.FileStream(imageFilePath , System.IO.FileMode.Open, System.IO.FileAccess.Read); mPictureBox.Image = System.Drawing.Image.FromStream(fs); } catch (Exception e) { if (fs != null) fs.Close(); }
显示图片成功之后,我们需要获取照片的宽度和高度,也就是像素大小
if(PictureBox.Image!=null){ imageWidth = mPictureBox.Image.Width; imageHeight = mPictureBox.Image.Height; }
准备工作都做好了.那么就需要处理图片框的鼠标事件了
private void ImageOnClickListener(object sender,MouseEventArgs e) { //为了防止图片框大小该表,先获取图片框的大小 int defWidth = mPictureBox.Width; int defHeight = mPictureBox.Height; //获取之后 我们需要获取鼠标点击在图片框的位置 也就是X 和 Y int _x = e.X; int _y = e.Y; //那么都获取之后就需要开始计算了 先计算倍数 double widthMultiple = 0; double heightMultiple = 0; if (imageWidth > defWidth) widthMultiple = imageWidth / defWidth; else widthMultiple = defWidth / defWidth - 1; if (imgaeHeight > defHeight) heightMultiple = imgaeHeight / defHeight; else heightMultiple = defHeight / imgaeHeight - 1; //最后相成 MessageBox.Show("X:" + (_x * widthMultiple) + " >> Y:" + (_y * heightMultiple), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); }
一般为了稳定,都将图片框的大小固定.小伙伴们可以试下哈~~~
相关文章推荐
- C# 编写命令行交互工具——实时输出_获取执行结果
- C# 读写文件操作
- C# ListView 编写 ListView 实体类
- C#文件流
- 【每日算法】删减字符获得最大回文符
- C#Winform实现高效率导入和导出Excel文件
- C#中菜单栏,工具栏,状态栏的学习总结
- C#将托管DLL嵌入exe文件
- 用C#模版匹配识别新教务系统登录验证码
- C#实验8(2)
- c#Gdi画图的两种方式
- protobuf V3 C# 中文机翻教程。
- C#—随机数3
- C# Excel几个常用排版例子
- C#中重新定义Console实现自动保存输出到文件
- C#实验8Windows应用编程
- C# Serializable
- 《Head First C#》学习 ---第一个实例中遇到的问题
- Log4net入门使用
- C#实现FTP基本功能源代码