1.wpf提供了
ScaleTransform,来进行缩放变换,提供了
TranslateTransform来进行位置变换(移动坐标)。
以下代码来自互联网,实现图片的缩放和平移。 也可以将图片改为其他元素。
2.xaml代码
<Window x:Class="Manager.Window4" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="600" Width="800" WindowState="Maximized" >
<Canvas Name="root">
<Grid>
<ScrollViewer Margin="100,100" HorizontalAlignment="Left" VerticalAlignment="Top">
<Image Name="img" Source="/manager;component/bin/Release/123.png" MouseDown="img_MouseDown" MouseWheel="img_MouseWheel" MouseMove="img_MouseMove" MouseUp="img_MouseUp" MouseLeave="img_MouseLeave" Stretch="Uniform" RenderOptions.BitmapScalingMode="NearestNeighbor" Canvas.Left="109" Canvas.Top="103">
<Image.RenderTransform>
<TransformGroup>
<ScaleTransform x:Name="sfr" />
<TranslateTransform x:Name="tlt" />
</TransformGroup>
</Image.RenderTransform>
</Image>
</ScrollViewer>
</Grid>
</Canvas>
</Window>
3.cs文件代码
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Manager
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class Window4 : Window
{
private bool isMouseLeftButtonDown = false;
Point previousMousePoint = new Point(0, 0);
public Window4()
{
InitializeComponent();
}
private void img_MouseDown(object sender, MouseButtonEventArgs e)
{
isMouseLeftButtonDown = true;
previousMousePoint = e.GetPosition(img);
}
private void img_MouseUp(object sender, MouseButtonEventArgs e)
{
isMouseLeftButtonDown = false;
}
private void img_MouseLeave(object sender, MouseEventArgs e)
{
isMouseLeftButtonDown = false;
}
private void img_MouseMove(object sender, MouseEventArgs e)
{
if (isMouseLeftButtonDown == true)
{
Point position = e.GetPosition(img);
tlt.X += position.X - this.previousMousePoint.X;
tlt.Y += position.Y - this.previousMousePoint.Y;
}
}
private void img_MouseWheel(object sender, MouseWheelEventArgs e)
{
Point centerPoint = e.GetPosition(img);
double val = (double)e.Delta / 2000; //描述鼠标滑轮滚动
if (sfr.ScaleX < 0.3 && sfr.ScaleY < 0.3 && e.Delta < 0)
{
return;
}
sfr.CenterX = centerPoint.X;
sfr.CenterY = centerPoint.Y;
sfr.ScaleX += val;
sfr.ScaleY += val;
}
}
}