C# 編寫點擊圖片框計算出在文件中的像素點

分類:編程 時間:2017-02-03

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);
        }

一般為了穩定,都將圖片框的大小固定.小夥伴們可以試下哈~~~



Tags: 點擊圖片 private 框計算 null 照片

文章來源:


ads
ads

相關文章
ads

相關文章

ad