C# 如何垂直翻转路径几何体?
我有一个要垂直翻转的路径几何体。我尝试了以下方法,但不起作用,我是否遗漏了什么C# 如何垂直翻转路径几何体?,c#,wpf,C#,Wpf,我有一个要垂直翻转的路径几何体。我尝试了以下方法,但不起作用,我是否遗漏了什么 PathGeometry myPathGeometry = new PathGeometry(); myPathGeometry.Figures.Add(myPathFigure); PathGeometry flipMyPathGeometry = new PathGeometry(); ScaleTransform transform = new ScaleTransform(0, -1); flipMyPath
PathGeometry myPathGeometry = new PathGeometry();
myPathGeometry.Figures.Add(myPathFigure);
PathGeometry flipMyPathGeometry = new PathGeometry();
ScaleTransform transform = new ScaleTransform(0, -1);
flipMyPathGeometry = Geometry.Combine(Geometry.Empty, myPathGeometry, GeometryCombineMode.Union, transform);
只需设置PathGeometry的
变换
属性:
var myPathGeometry = new PathGeometry();
myPathGeometry.Figures.Add(myPathFigure);
myPathGeometry.Transform = new ScaleTransform(1, -1);
请注意,您可能还需要设置ScaleTransform的
CenterY
属性以获得正确的垂直对齐。一个大问题是宽度将为零。
X和Y标度是影响因素。就像乘数一样。任何乘以零的东西都是零。
因此
会给你一些没有宽度的东西
您可能想要相同的宽度,因此:
ScaleTransform(1, -1);
如果你想让物体翻转到它的中心,那可能还有另一个问题,但至少当你使用它时,它应该显示出来
CenterY的计算可能不那么明显。可以使用几何体的边界计算几何体的高度
由于要创建新的pathgeometry,可能需要保留原始路径而不进行任何变换
我将一些代码放在一起,从资源中操纵几何体,并使用它向画布添加路径
标记:
<Window.Resources>
<Geometry x:Key="Star">
M16.001007,0L20.944,10.533997 32,12.223022 23.998993,20.421997 25.889008,32 16.001007,26.533997 6.1109924,32 8,20.421997 0,12.223022 11.057007,10.533997z
</Geometry>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button x:Name="myButton" Click="MyButton_Click">
</Button>
<Canvas Grid.Column="1" Name="myCanvas"/>
</Grid>
“安迪”和“克莱门斯”都给出了正确的答案。我没有得到预期形状的原因是我没有注意到形状在屏幕区域之外。但是,我使用了Andy的解决方案,因为我需要保持原始形状。此外,他还通知我要创建新边界。我在他的回答中唯一改变的是新边界的值,因为他使用的边界形状仍然在屏幕区域之外
double newY = (bounds.Bottom - bounds.Top);
谢谢,不知什么原因,我最终得到了相同的原始图形数据!抱歉,您当然会将变换应用于原始PathGeometry。我已经编辑了答案。我已经将变换应用于原始PathGeometry,并且它不会翻转形状。这是我的期望,如果我错了,请纠正我。使用
ScaleTransform(1,-1)
后,新的Y值不应该与原始值相同,对吗?!不,值保持不变。只是渲染发生了变化。你是对的,我想保留原始图像而不进行任何变换。然而,我知道这没有意义,但在我的例子中,翻转的形状具有与原始geom
相同的数据。它不会因为某种原因被翻转!谢谢你,安迪,我知道我错了。我会在答覆中解释。
private void MyButton_Click(object sender, RoutedEventArgs e)
{
Geometry geom = this.Resources["Star"] as Geometry;
Geometry flipped = geom.Clone();
var bounds = geom.Bounds;
double halfY = (bounds.Bottom - bounds.Top) / 2.0;
flipped.Transform = new ScaleTransform(1, -1, 0, halfY );
PathGeometry pg = PathGeometry.CreateFromGeometry(flipped);
var path = new System.Windows.Shapes.Path {Data=pg, Fill= System.Windows.Media.Brushes.Red };
this.myCanvas.Children.Add(path);
}
double newY = (bounds.Bottom - bounds.Top);