首页 > 代码库 > 修剪Canvas中的内容
修剪Canvas中的内容
用Canvas绘制图形时,如果图形的大小超过Canvas时也能够显示出来,如下图所示:
有时这种效果不是我们要的,如何能达到如下图所示的效果:
Xaml代码如下:
xmlns:util="clr-namespace:Util"
?
<Grid x:Name="LayoutRoot" Background="White" Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Canvas Grid.Column="0" Background="Aqua" Margin="20" >
<Ellipse Fill="Red" Canvas.Top="-20" Canvas.Left="-20" Width="200" Height="200"/>
</Canvas>
<Canvas Grid.Column="1" Background="Aqua" Margin="20" util:Clip.ToBounds="true">
<Ellipse Fill="Red" Canvas.Top="-20" Canvas.Left="-20" Width="200" Height="200"/>
</Canvas>
</Grid>
CS代码如下:
namespace Util
{
public class Clip
{
public static bool GetToBounds(DependencyObject depObj)
{
return (bool)depObj.GetValue(ToBoundsProperty);
}
?
public static void SetToBounds(DependencyObject depObj, bool clipToBounds)
{
depObj.SetValue(ToBoundsProperty, clipToBounds);
}
?
public static readonly DependencyProperty ToBoundsProperty =
DependencyProperty.RegisterAttached("ToBounds", typeof(bool),
typeof(Clip), new PropertyMetadata(false, OnToBoundsPropertyChanged));
?
private static void OnToBoundsPropertyChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
FrameworkElement fe = d as FrameworkElement;
if (fe != null)
{
ClipToBounds(fe);
?
fe.Loaded += new RoutedEventHandler(fe_Loaded);
fe.SizeChanged += new SizeChangedEventHandler(fe_SizeChanged);
}
}
?
private static void ClipToBounds(FrameworkElement fe)
{
if (GetToBounds(fe))
{
fe.Clip = new RectangleGeometry()
{
Rect = new Rect(0, 0, fe.ActualWidth, fe.ActualHeight)
};
}
else
{
fe.Clip = null;
}
}
?
static void fe_SizeChanged(object sender, SizeChangedEventArgs e)
{
ClipToBounds(sender as FrameworkElement);
}
?
static void fe_Loaded(object sender, RoutedEventArgs e)
{
ClipToBounds(sender as FrameworkElement);
}
}
}
修剪Canvas中的内容