您的位置:首页 > 编程语言 > C#

C# 编写点击图片框计算出在文件中的像素点

2016-05-26 00:00 483 查看
OK,今天的教程我们需要做的是在图片框中显示一张图片,然后我们点击图片上任意位置,计算出在该图片实际点击为的位置。

如我选择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);
}


一般为了稳定,都将图片框的大小固定.小伙伴们可以试下哈~~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: