user16881171
user16881171

Reputation:

how to set the limit for the amount you can zoom in and out

Id like to make it so that you can only zoom in and out a certain amount, what do i add to do that

    private void main_MouseWheel(object sender, MouseWheelEventArgs e)
    {
        MatrixTransform? m = grid.RenderTransform as MatrixTransform;
        Point pos1 = e.GetPosition(grid);
        double scale = e.Delta >= 0 ? 1.1 : 1 / 1.1;
        Matrix mm = m.Matrix;
        mm.ScaleAt(scale, scale, pos1.X, pos1.Y);
        m.Matrix = mm;
    }

This is the code for zooming onto the mouse position on the grid

<Grid>
    <Viewbox>
        <Grid x:Name="grid">
            <Grid.RenderTransform>
                <MatrixTransform/>
            </Grid.RenderTransform>
        </Grid>
    </Viewbox>
</Grid>

This is the xaml for the grid

Upvotes: 0

Views: 69

Answers (1)

mm8
mm8

Reputation: 169160

Check the Matrix against pre-defined min and max values. Something like this:

private const double MinScale = 0.2;
private const double MaxScale = 0.8;
private void main_MouseWheel(object sender, MouseWheelEventArgs e)
{
    MatrixTransform? m = grid.RenderTransform as MatrixTransform;
    Point pos1 = e.GetPosition(grid);
    double scale = e.Delta >= 0 ? 1.1 : 1 / 1.1;
    Matrix mm = m.Matrix;
    if (mm.M11 < MinScale)
        mm.M11 = MinScale;
    else if (mm.M11 > MaxScale)
        mm.M11 = MaxScale;

    if (mm.M22 < MinScale)
        mm.M22 = MinScale;
    else if (mm.M22 > MaxScale)
        mm.M22 = MaxScale;

    mm.ScaleAt(scale, scale, pos1.X, pos1.Y);
    m.Matrix = mm;
}

Or use a ScaleTransform:

private const double MinScale = 0.2;
private const double MaxScale = 0.8;
private double _scale = 1.0;
private void main_MouseWheel(object sender, MouseWheelEventArgs e)
{
    ScaleTransform? s = grid.RenderTransform as ScaleTransform;
    _scale += e.Delta > 0 ? 0.1 : -0.1;
    if (_scale < MinScale)
        _scale = MinScale;
    else if (_scale > MaxScale)
        _scale = MaxScale;
    s.ScaleX = _scale;
    s.ScaleY = _scale;

}

XAML:

<Grid>
    <Viewbox>
        <Grid x:Name="grid" RenderTransformOrigin="0.5,0.5">
            <Grid.RenderTransform>
                <ScaleTransform/>
            </Grid.RenderTransform>
            <TextBlock Text="test" />
        </Grid>
    </Viewbox>
</Grid>

Upvotes: 1

Related Questions