我用wpf在C#中编写了一个小应用程序。我的目标是在图片上画一个圆。只要按下鼠标按钮,圆圈就应该是可移动的,并且只有在用户释放鼠标按钮之后,才应该最终绘制圆圈。为了绘制椭圆,我使用DrawEllipse。
grf.DrawEllipse(
myPen,
(float)xOriginal - 25,
(float)yOriginal - 25,
radius,
radius
);
释放鼠标后,应绘制圆圈。然后我想拿起坐标并保存。
我的想法是使用MouseDown,MouseMove和MouseUp。 MouseDown记录该点击。使用MouseMove,每次都应重画圆圈,而使用MouseUp,则应最后绘制圆圈。
我的问题是,使用MouseMove会一次又一次绘制圆,并且不会删除圆。另外,它被难以置信地延迟了。有更好的解决方案
这是我快速又肮脏的代码段:
bool registerClick = false;
private void Image_imageBox_MouseregisterClick(object sender, MouseButtonEventArgs e)
{
registerClick = true;
}
private void Image_imageBox_MouseMove(object sender, MouseEventArgs e)
{
if (registerClick)
{
Pen myPen = new Pen(Color.FromArgb(255, 0, 0, 0), 10);
int radius = 50;
Bitmap b1 = _detektion.BildOriginal.Bitmap;
using (Graphics grf = Graphics.FromImage(b1))
{
// zeichne denkreis ein
grf.DrawEllipse(
myPen,
((float)e.GetPosition(imageBox_Image).X - 25,
(float)e.GetPosition(imageBox_Image).X - 25,
radius,
radius
);
}
imageBox_Image.Source = DGX_Body.Utility.Images.ConvertBitmapToBitmapImage(b1);
}
}
private void Image_imageBox_MouseUp(object sender, MouseButtonEventArgs e)
{
Console.WriteLine("Up!");
registerClick = false;
}
能帮我吗? 谢谢
答案 0 :(得分:3)
这是使用鼠标输入的“画布”中椭圆的一个非常基本的例子。
XAML:
<Grid>
<Image Source="C:\Users\Public\Pictures\Sample Pictures\Koala.jpg"
Stretch="None" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<Canvas Background="Transparent"
MouseLeftButtonDown="CanvasMouseLeftButtonDown"
MouseLeftButtonUp="CanvasMouseLeftButtonUp"
MouseMove="CanvasMouseMove"/>
</Grid>
事件处理程序后面的代码:
private Ellipse currentEllipse;
private void CanvasMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var canvas = (Canvas)sender;
var pos = e.GetPosition(canvas);
canvas.CaptureMouse();
currentEllipse = new Ellipse
{
Width = 50,
Height = 50,
Margin = new Thickness(-25, -25, 0, 0),
Stroke = Brushes.White,
StrokeThickness = 3
};
Canvas.SetLeft(currentEllipse, pos.X);
Canvas.SetTop(currentEllipse, pos.Y);
canvas.Children.Add(currentEllipse);
}
private void CanvasMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
var canvas = (Canvas)sender;
canvas.ReleaseMouseCapture();
currentEllipse = null;
}
private void CanvasMouseMove(object sender, MouseEventArgs e)
{
if (currentEllipse != null)
{
var canvas = (Canvas)sender;
var pos = e.GetPosition(canvas);
Canvas.SetLeft(currentEllipse, pos.X);
Canvas.SetTop(currentEllipse, pos.Y);
}
}
有了这个小小的改动,您还可以选择现有的椭圆:
private void CanvasMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var canvas = (Canvas)sender;
var pos = e.GetPosition(canvas);
canvas.CaptureMouse();
currentEllipse = e.OriginalSource as Ellipse;
if (currentEllipse == null)
{
currentEllipse = new Ellipse
{
Width = 50,
Height = 50,
Margin = new Thickness(-25, -25, 0, 0),
Fill = Brushes.Transparent,
Stroke = Brushes.White,
StrokeThickness = 3
};
canvas.Children.Add(currentEllipse);
}
Canvas.SetLeft(currentEllipse, pos.X);
Canvas.SetTop(currentEllipse, pos.Y);
}