/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
WPFWindow.MouseWheel += MainWindow_MouseWheel;
image.MouseLeftButtonDown += image_MouseLeftButtonDown;
image.MouseLeftButtonUp += image_MouseLeftButtonUp;
image.MouseMove += image_MouseMove;
}
private Point origin;
private Point start;
/// <summary>
/// 图片路径
/// </summary>
/// <param name="fileName"></param>
public void SetSource(string fileName)
{
image.Source = new BitmapImage(new Uri(fileName));
}
/// <summary>
/// 程序高度和宽度
/// </summary>
/// <param name="height"></param>
/// <param name="width"></param>
public void setHeight_Width(int height,int width)
{
WPFWindow.Height = height;
WPFWindow.Width = width;
}
private void image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
image.ReleaseMouseCapture();
}
private void image_MouseMove(object sender, MouseEventArgs e)
{
if (!image.IsMouseCaptured) return;
Point p = e.MouseDevice.GetPosition(border);
Matrix m = image.RenderTransform.Value;
m.OffsetX = origin.X + (p.X - start.X);
m.OffsetY = origin.Y + (p.Y - start.Y);
image.RenderTransform = new MatrixTransform(m);
}
private void image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (image.IsMouseCaptured) return;
image.CaptureMouse();
start = e.GetPosition(border);
origin.X = image.RenderTransform.Value.OffsetX;
origin.Y = image.RenderTransform.Value.OffsetY;
}
private void MainWindow_MouseWheel(object sender, MouseWheelEventArgs e)
{
Point p = e.MouseDevice.GetPosition(image);
Matrix m = image.RenderTransform.Value;
if (e.Delta > 0)
m.ScaleAtPrepend(1.1, 1.1, p.X, p.Y);
else
m.ScaleAtPrepend(1 / 1.1, 1 / 1.1, p.X, p.Y);
image.RenderTransform = new MatrixTransform(m);
}
/*xaml 页面*/
<UserControl x:Class="WpfControlLibrary1.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
x:Name="WPFWindow"
d:DesignHeight="610" d:DesignWidth="674"
>
<Grid>
<Border Grid.Row="1" Name="border" ClipToBounds="True">
<Image Name="image" Opacity="1" />
</Border>
</Grid>
/**/
本人网上当的代码, 现在想新增功能呢,就是图片滚动缩放 到图片原本大小就不缩放了,拖动到图片的边角就不拖动了,