2011-05-24 58 views
1

我使用PictureEdit(DevExpress控件)作爲某種形式的子項。我試圖使用MouseEventArgs座標屬性將一個像素繪製到加載的圖像上。發生無法在位圖上繪製

private void PictureEditorOnMouseMove(Object sender, MouseEventArgs e) 
{    
    if(e.Button == MouseButtons.Left) 
    { 
     (this.pictureEditor.Image as Bitmap).SetPixel(e.X, e.Y, this.colorPicker.Color);          
    } 
} 

ArgumentOutOfRangeException說,傳遞給SetPixel方法x(或y)參數不積極小於給定的位圖的Height財產更大& &。 我在考慮使用由bitmap.Widthbitmap.Height綁定的座標。

我該如何綁定它們?或者我做錯了什麼?

謝謝!

+0

當你調試時,e.X和e.Y有什麼值?他們在位圖的範圍內? – LueTm 2011-05-24 06:58:09

+0

你爲什麼要測試鼠標移動按鈕? – 2011-05-24 07:05:58

+0

@David不應該嗎? – lexeme 2011-05-24 07:19:08

回答

0

試試這個:

private void PictureEditorOnMouseMove(Object sender, MouseEventArgs e) 
{ 
    if(e.Button == MouseButtons.Left) 
    { 
     PictureEdit pce = sender as PictureEdit; 
     Bitmap bmpImage = pce.Image as Bitmap; 
     PictureEditViewInfo viewInfo = pce.GetViewInfo() as PictureEditViewInfo; 

     var p = new Point(
      (e.Location.X - viewInfo.PictureStartX) * bmpImage.Width/viewInfo.PictureRect.Width, 
      (e.Location.Y - viewInfo.PictureStartY) * bmpImage.Height/viewInfo.PictureRect.Height); 

     if (p.X >= 0 && p.X < bmpImage.Width && p.Y >= 0 && p.Y < bmpImage.Height) 
     { 
      bmpImage.SetPixel(p.X, p.Y, this.colorPicker.Color); 
     } 
     else 
     { 
      Console.WriteLine("Out bounds"); 
     } 
    } 
} 

請注意,您需要將鼠標位置轉換成位圖的aproximate像素位置,考慮到PictureEdit的SizeMode。這是在示例代碼中創建新點時完成的。