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

OK,今天的教程咱们须要作的是在图片框中显示一张图片,而后咱们点击图片上任意位置,计算出在该图片实际点击为的位置。c#


如我选择720 * 1280的图片,而图片框的大小为 360 *640,那么要怎样计算出位置呢。code


OK,那么开始.orm


首先须要添加一个图片框,以后咱们须要给该图片框添加一个鼠标,该鼠标事件是为了对点击位置进行处理。教程


首先须要作的是将图片显示到图片框中,因为须要释放资源,这里不直接显示,而是经过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);
        }
通常为了稳定,都将图片框的大小固定.小伙伴们能够试下哈~~~
相关文章
相关标签/搜索