gpt4 book ai didi

C# WPF - 拖动图像

转载 作者:行者123 更新时间:2023-11-30 13:22:54 25 4
gpt4 key购买 nike

我正在尝试获得一些简单的功能,即从文件中获取图像,将其添加到 Canvas ,然后允许用户左键单击(并按住)图像,然后将其拖到 Canvas 上(即更新图像的位置)

这是我到目前为止的内容,我应该添加什么?

private void btnAddImage_Click(object sender, RoutedEventArgs e) {
try {
System.Windows.Forms.OpenFileDialog open = new System.Windows.Forms.OpenFileDialog();
open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
if (open.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
PictureBox PictureBox1 = new PictureBox();
PictureBox1.Image = new Bitmap(open.FileName);
myCanvas.children.add(PictureBox1);
}
}
catch (Exception) { throw new ApplicationException("Failed loading image"); }
}

最佳答案

您可以添加 Image控制 Canvas 并根据鼠标输入修改其 LeftTop 属性。

XAML:

<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Canvas x:Name="canvas"
MouseLeftButtonDown="CanvasMouseLeftButtonDown"
MouseLeftButtonUp="CanvasMouseLeftButtonUp"
MouseMove="CanvasMouseMove"/>
<Button Grid.Row="1" Content="Add Image" Click="AddButtonClick"/>
</Grid>

代码隐藏:

private void AddButtonClick(object sender, RoutedEventArgs e)
{
var dialog = new Microsoft.Win32.OpenFileDialog();
dialog.Filter =
"Image Files (*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";

if ((bool)dialog.ShowDialog())
{
var bitmap = new BitmapImage(new Uri(dialog.FileName));
var image = new Image { Source = bitmap };
Canvas.SetLeft(image, 0);
Canvas.SetTop(image, 0);
canvas.Children.Add(image);
}
}

private Image draggedImage;
private Point mousePosition;

private void CanvasMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var image = e.Source as Image;

if (image != null && canvas.CaptureMouse())
{
mousePosition = e.GetPosition(canvas);
draggedImage = image;
Panel.SetZIndex(draggedImage, 1); // in case of multiple images
}
}

private void CanvasMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (draggedImage != null)
{
canvas.ReleaseMouseCapture();
Panel.SetZIndex(draggedImage, 0);
draggedImage = null;
}
}

private void CanvasMouseMove(object sender, MouseEventArgs e)
{
if (draggedImage != null)
{
var position = e.GetPosition(canvas);
var offset = position - mousePosition;
mousePosition = position;
Canvas.SetLeft(draggedImage, Canvas.GetLeft(draggedImage) + offset.X);
Canvas.SetTop(draggedImage, Canvas.GetTop(draggedImage) + offset.Y);
}
}

关于C# WPF - 拖动图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17035225/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com