0

如何使用几何和 ScaleTransform 在 Silverlight 中实现缩放到特定点?你能建议一些算法,以便我可以实现这一点吗?我的逻辑是错误的。我认为设置缩放的中心点会遇到一些麻烦。

这是我在 xaml 文件中的几何数据

<Canvas x:Name="LayoutRoot"  Background="Orchid" MouseWheel="PathDraw_OnMouseWheel">
  <Path x:Name="PathDraw" Stroke="Brown"  StrokeThickness="1" Margin="200,200,0,0">
    <Path.Data>
      <RectangleGeometry x:Name="rect"  Rect="80 80 80 80"/>
    </Path.Data>
  </Path>
</Canvas>

下面是缩放逻辑。

private static int ZoomSteps = 0;

    private static double centerX = 0;
    private static double centerY = 0;
    private double zoomCoeff = 1.1;

    private void PathDraw_OnMouseWheel(object sender, MouseWheelEventArgs e)
    {
        double delta = e.Delta;
        if (scaleX != 1)
        {
            scaleX = delta >= 0 ? scaleX * zoomCoeff : (scaleX <= 1 ? 1 : scaleX / zoomCoeff);
            scaleY = delta >= 0 ? scaleY * zoomCoeff : (scaleY <= 1 ? 1 : scaleY/zoomCoeff);
        }
        else
        {
            scaleX = scaleY = delta >= 0 ? zoomCoeff : 1;
        }

        scale = new ScaleTransform { ScaleX = scaleX, ScaleY = scaleY,
                                     CenterX = e.GetPosition(PathDraw).X,
                                     CenterY = e.GetPosition(PathDraw).Y

        };
        rect.Transform = scale;
    }

谢谢

4

1 回答 1

0

而不是在路径上有一个边距和一个具有固有偏移量的几何图形(矩形左上角在 80,80),您应该使用两个变换将缩放与平移分开:

<Canvas x:Name="LayoutRoot"  Background="AliceBlue" MouseWheel="PathDraw_OnMouseWheel">
    <Path x:Name="PathDraw" Stroke="Brown" StrokeThickness="1">
        <Path.Data>
            <RectangleGeometry x:Name="rect" Rect="0 0 80 80">
                <RectangleGeometry.Transform>
                    <TransformGroup>
                        <ScaleTransform x:Name="scaleTransform"/>
                        <TranslateTransform x:Name="translateTransform"
                                            X="100" Y="100"/>
                    </TransformGroup>
                </RectangleGeometry.Transform>
            </RectangleGeometry>
        </Path.Data>
    </Path>
</Canvas>

有了这个,你的 MouseWheel 事件处理程序变得像这样简单:

private double zoomCoeff = 1.1;

private void PathDraw_OnMouseWheel(object sender, MouseWheelEventArgs e)
{
    var deltaScale = (e.Delta > 0) ? zoomCoeff : (1d / zoomCoeff);
    var position = e.GetPosition((UIElement)sender);
    var dx = position.X - translateTransform.X;
    var dy = position.Y - translateTransform.Y;

    translateTransform.X = position.X - deltaScale * dx;
    translateTransform.Y = position.Y - deltaScale * dy;
    scaleTransform.ScaleX *= deltaScale;
    scaleTransform.ScaleY *= deltaScale;
}

您现在还可以在 MouseMove 处理程序中独立操作平移以拖动矩形。

于 2013-10-21T12:39:28.020 回答