C#WPF - 拖动图像 [英] C# WPF -Drag an image
本文介绍了C#WPF - 拖动图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图获得一些简单的功能,从文件中获取图像,将其添加到Canvas,然后允许用户左键单击(并保持)图像,然后将其拖动到Canvas(即更新图像的位置)
I am trying to get some simple functionality of getting an image from a file, adding it to a Canvas, and then allowing a user to left-click (and hold) on the image and then drag it around the Canvas (i.e. updating the image's location)
这是我到目前为止所做的,我应该添加什么?
Here's what I have so far, what should I be adding?
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"); }
}
推荐答案
您可以添加< a href =http://msdn.microsoft.com/en-us/library/system.windows.controls.image.aspx>图像控制到画布并修改其左鼠标输入时
和 Top
属性。
You may add an Image control to the Canvas and modify its Left
and Top
properties on mouse input.
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 - 拖动图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文