I'm writing an image control with zoom, and wrap into a usercontrol.
<UserControl x:Class="WpfApp20.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"
xmlns:local="clr-namespace:WpfApp20"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid Background="Green">
<Grid x:Name="gridMain" MouseWheel="gridMain_MouseWheel">
<Viewbox Stretch="Uniform">
<Grid x:Name="SIGrid">
<Grid.RenderTransform >
<TransformGroup >
<MatrixTransform x:Name="MatrixTransform" />
</TransformGroup>
</Grid.RenderTransform>
<Image x:Name="PART_MainImage" Source="/Grid.png" RenderOptions.BitmapScalingMode="NearestNeighbor" RenderOptions.EdgeMode="Aliased" SnapsToDevicePixels="True" Stretch="Uniform" StretchDirection="Both" Visibility="Visible">
</Image>
</Grid>
</Viewbox>
</Grid>
</Grid>
</UserControl>
private void gridMain_MouseWheel(object sender, MouseWheelEventArgs e)
{
try
{
if (MatrixTransform == null)
return;
var pos = e.GetPosition(PART_MainImage);
var scale = e.Delta > 0 ? 1.1 : 1 / 1.1;
var matrix = MatrixTransform.Matrix;
if (matrix.M11 <= 0.1 && e.Delta < 0)
return;
MatrixTransform.Matrix = new Matrix(scale, 0, 0, scale, pos.X - (scale * pos.X), pos.Y - (scale * pos.Y)) * matrix;
}
catch (Exception ex)
{
}
}
Then in MainWindow, I just put it into a grid.
<Grid Background="Red"/>
<Grid Grid.Row="1">
<local:UserControl1/>
</Grid>
So when I zoom in, the image goes out of the usercontrol bounds, it should always in the green area.
How to fix?
I made a sample here.