我想在WPF中为矩形的圆角设置颜色。
以下是我希望拥有的一个例子:
目前,我已经使用了此代码:
<Rectangle x:Name="rect" Fill="Transparent" RadiusY="10" RadiusX="10"/>
答案 0 :(得分:3)
更简单的方法:
<Rectangle Fill="Red" Height="200" Width="200" >
<Rectangle.Clip >
<CombinedGeometry GeometryCombineMode="Exclude">
<CombinedGeometry.Geometry1>
<RectangleGeometry Rect="0,0,200,200"/>
</CombinedGeometry.Geometry1>
<CombinedGeometry.Geometry2>
<EllipseGeometry x:Name="transparentRect" Center="100 100" RadiusX="120" RadiusY="120"/>
</CombinedGeometry.Geometry2>
</CombinedGeometry>
</Rectangle.Clip>
</Rectangle>
注意
如果更改矩形的大小,则必须调整几何的“矩形”和“半径 - 值”,以便显示正确的比例。
我在几分钟内完成了这项工作,因此可能还有改进的余地。
干杯
修改强>
对于一个完全令人满意的方法,我已经为你做了2个转换器
<强>代码强>
public class RectangleConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
var recta = value as Rectangle;
if (recta == null) return null;
return new Rect { X = 0, Y = 0, Height = recta.ActualHeight, Width = recta.ActualWidth };
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
throw new NotImplementedException();
}
}
public class ElipseGeoConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
var recta = value as Rectangle;
if (recta == null) return null;
return new EllipseGeometry(new Point(recta.ActualWidth / 2, recta.ActualHeight / 2), recta.ActualWidth / 3 * 2,
recta.ActualHeight / 3 * 2);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
throw new NotImplementedException();
}
}
<强>用法强>
<Rectangle Fill="Red" Height="100" Width="100" >
<Rectangle.Clip >
<CombinedGeometry GeometryCombineMode="Exclude">
<CombinedGeometry.Geometry1>
<RectangleGeometry>
<RectangleGeometry.Rect>
<Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type Rectangle}}" Converter="{StaticResource RectangleConverter}"></Binding>
</RectangleGeometry.Rect>
</RectangleGeometry>
</CombinedGeometry.Geometry1>
<CombinedGeometry.Geometry2>
<Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type Rectangle}}" Converter="{StaticResource GeoConverter}"/>
</CombinedGeometry.Geometry2>
</CombinedGeometry>
</Rectangle.Clip>
</Rectangle>
答案 1 :(得分:2)
将四个圆角绘制为四个独立的Path元素可能更简单:
<Grid>
<Path HorizontalAlignment="Left" VerticalAlignment="Top" Fill="Red"
Data="M0,0 L10,0 A10,10 0 0 0 0,10Z"/>
<Path HorizontalAlignment="Right" VerticalAlignment="Top" Fill="Red"
Data="M0,0 L0,10 A10,10 0 0 0 -10,0Z"/>
<Path HorizontalAlignment="Left" VerticalAlignment="Bottom" Fill="Red"
Data="M0,0 L10,0 A10,10 0 0 1 0,-10Z"/>
<Path HorizontalAlignment="Right" VerticalAlignment="Bottom" Fill="Red"
Data="M0,0 L0,-10 A10,10 0 0 1 -10,0Z"/>
</Grid>