【问题标题】:Changed MatrixTransform result control out of bounds将 MatrixTransform 结果控制更改为越界
【发布时间】:2022-01-20 17:35:28
【问题描述】:

我正在编写一个带缩放功能的图像控件,并包装到一个用户控件中。

<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)
            {

            }
        }

然后在MainWindow中,我只是把它放到一个网格中。

<Grid Background="Red"/>

<Grid  Grid.Row="1">
    <local:UserControl1/>
</Grid>

所以当我放大时,图像超出了用户控件的范围,它应该总是在绿色区域。

如何解决?

我做了一个样本here

【问题讨论】:

标签: c# wpf xaml transform


【解决方案1】:

终于,ClipToBounds救了我。

<Grid Background="Green" ClipToBounds="True">

【讨论】:

    猜你喜欢
    • 2023-01-10
    • 2011-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 2016-08-27
    • 2017-01-30
    相关资源
    最近更新 更多