单击时,寄生点显示在WPF画布上
我在WPF中使用画布时遇到问题。我使用此代码的一个稍加修改的版本: 代码如下: Xaml:单击时,寄生点显示在WPF画布上,wpf,canvas,drawing,Wpf,Canvas,Drawing,我在WPF中使用画布时遇到问题。我使用此代码的一个稍加修改的版本: 代码如下: Xaml: <Canvas x:Name="cnvImage" Width="800"> <Image MouseDown="img_MouseDown" MouseMove="img_MouseMove" MouseUp="img_MouseUp" Source="/Images/CapturedImage.png"> <
<Canvas x:Name="cnvImage" Width="800">
<Image MouseDown="img_MouseDown"
MouseMove="img_MouseMove"
MouseUp="img_MouseUp"
Source="/Images/CapturedImage.png">
</Image>
</Canvas>
我想画矩形,但有一个问题:如果我只是在画布上左键单击,它会画一个小的红色点,似乎无法删除
这是从哪里来的?我怎样才能摆脱它
编辑:问题已经解决。我认为您需要检查
img\u MouseDown
和img\u MouseUp
中的位置,如果这些位置相等,那么您应该删除您创建的矩形
因为你在鼠标向下添加了一个strokethickness为2的矩形,你总是会在代码中得到一个实际宽度和高度至少为2的矩形。我认为你需要检查mousedown和mouseup中的位置,如果这些位置相等,那么你应该删除你创建的矩形。它可以工作:D这很奇怪,当我遇到“如果(宽度问题是,你已经在鼠标向下添加了一个矩形,并将strokethickness设置为2,因此你将始终得到一个宽度和高度至少为2的矩形。我将发布我的评论作为答案,如果它对你有帮助,你可以接受。谢谢,是的,但是2仍然低于10,那么为什么?我看不出如果在您发布的e代码。您能发布该代码吗?您能详细说明一下吗?我用里面的解决方案编辑了代码。您还可以检查ActualWidth和ActualHeight属性是否大于要删除的特定数字,或者是否为矩形,因为Width和Height属性不返回数值。
private Point startPoint;
private Rectangle rectSelectArea;
private void img_MouseDown(object sender, MouseButtonEventArgs e)
{
startPoint = e.GetPosition(cnvImage);
// Remove the drawn rectanglke if any.
// At a time only one rectangle should be there
if (rectSelectArea != null)
cnvImage.Children.Remove(rectSelectArea);
// Initialize the rectangle.
// Set border color, fill and width
rectSelectArea = new Rectangle
{
Stroke = Brushes.Red,
StrokeThickness = 2,
Fill = Brushes.Transparent
};
Canvas.SetLeft(rectSelectArea, startPoint.X);
Canvas.SetTop(rectSelectArea, startPoint.Y);
cnvImage.Children.Add(rectSelectArea);
}
private void img_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Released || rectSelectArea == null)
return;
var pos = e.GetPosition(cnvImage);
// Set the position of rectangle
var x = Math.Min(pos.X, startPoint.X);
var y = Math.Min(pos.Y, startPoint.Y);
// Set the dimension of the rectangle
var w = Math.Max(pos.X, startPoint.X) - x;
var h = Math.Max(pos.Y, startPoint.Y) - y;
rectSelectArea.Width = w;
rectSelectArea.Height = h;
Canvas.SetLeft(rectSelectArea, x);
Canvas.SetTop(rectSelectArea, y);
}
private void img_MouseUp(object sender, MouseButtonEventArgs e)
{
private void img_MouseUp(object sender, MouseButtonEventArgs e)
{
//EDIT : this condition SOLVES the problem
if (e.GetPosition(cnvImage) == startPoint)
cnvImage.Children.Remove(rectSelectArea);
rectSelectArea = null;
}