wpf 如何设置缩放量的限制

b09cbbtk  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(133)

我想使它,使您只能放大和缩小一定的数额,我添加什么做这一点

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;
    }

这是用于缩放到网格上的鼠标位置的代码

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

这是网格的xaml。

d8tt03nd

d8tt03nd1#

根据预定义的最小值和最大值检查Matrix

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;
}

或者使用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>

相关问题