2011-05-24 75 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。这是在示例代码中创建新点时完成的。