您需要使用橢圓的Clip
屬性。您可以使用多邊形的RenderedGeometry
屬性作爲剪輯幾何體的來源。但是,考慮到您將它們放置在畫布內,您需要考慮其位置。
讓我們創造出剪輯一個形狀與另一個多值轉換器:
public class ClipWithConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var clipped = (Shape)values[0];
var clip = (Shape)values[1];
var clippedPos = new Point(Canvas.GetLeft(clipped), Canvas.GetTop(clipped));
var clipPos = new Point(Canvas.GetLeft(clip), Canvas.GetTop(clip));
var deltaVector = clipPos - clippedPos;
var geometry = clip.RenderedGeometry.Clone();
geometry.Transform = new TranslateTransform(deltaVector.X, deltaVector.Y);
return geometry;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
現在我們可以在XAML中使用它:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1">
<Window.Resources>
<local:ClipWithConverter x:Key="ClipWithConverter"/>
</Window.Resources>
<Canvas>
<Ellipse x:Name="Ellipse" Canvas.Left="50" Canvas.Top="0"
Fill="Red" Width="250" Height="250">
<Ellipse.Clip>
<MultiBinding Converter="{StaticResource ClipWithConverter}">
<Binding ElementName="Ellipse"/>
<Binding ElementName="Polygon"/>
</MultiBinding>
</Ellipse.Clip>
</Ellipse>
<Polygon x:Name="Polygon" Canvas.Left="10" Canvas.Top="10"
Stroke="Black" StrokeThickness="3"
Points="100 0, 300 150, 150 300, 0 100"/>
</Canvas>
</Window>
然而,我們的轉換器被稱爲有點太早,當幾何圖形尚未渲染時,讓我們在構造函數中添加一點小技巧:
public MainWindow()
{
InitializeComponent();
Dispatcher.InvokeAsync(
BindingOperations.GetMultiBindingExpression(Ellipse, ClipProperty).UpdateTarget,
DispatcherPriority.Background);
}
這裏的結果:
我會離開更新爲exircise適當結合。
超級,有它的工作。謝謝! – CarlM