MatrixTransform与画布的宽度/高度相结合

时间:2014-03-04 11:09:26

标签: wpf canvas scrollviewer matrix-transform

放大画布上的绘图时,我需要显示滚动条 Canvas在ScrollViewer中,我增加了Canvas的宽度/高度,以便显示scollbars(否则它们不会出现)。

要使用因子1.1放大,请使用以下代码:

Matrix m = this.LayoutTransform.Value;
if (e.Delta > 0) f = 1.1;
else f = 1.0 / 1.1;
m.Scale(f, f);
this.LayoutTransform = new MatrixTransform(m);
this.Height = this.ActualHeight * f;
this.Width = this.ActualWidth * f;

事实证明,画布变得太大了。图形放大10%,但宽度似乎比1.1的平方更加20%。所以我使用Math.Sqrt(f);代替f

有人可以解释为什么会这样吗?

1 个答案:

答案 0 :(得分:1)

您应该只更改Canvas的LayoutTransform,就像在这个简化示例中一样:

<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
    <Canvas Width="1000" Height="1000" Background="Transparent"
            MouseWheel="Canvas_MouseWheel">
        <Canvas.LayoutTransform>
            <MatrixTransform/>
        </Canvas.LayoutTransform>
    </Canvas>
</ScrollViewer>

MouseWheel事件处理程序:

private void Canvas_MouseWheel(object sender, MouseWheelEventArgs e)
{
    var element = (FrameworkElement)sender;
    var transform = (MatrixTransform)element.LayoutTransform;
    var matrix = transform.Matrix;
    var scale = e.Delta >= 0d ? 1.1 : (1d / 1.1);

    matrix.Scale(scale, scale);
    transform.Matrix = matrix;

    e.Handled = true;
}