自定义形状,为包含的几何图形wpf设置不同的颜色
本文关键字:设置 wpf 颜色 几何图形 自定义 包含 | 更新日期: 2023-09-27 17:57:32
我创建了一个自定义的Shape
,它由Rectangle
和里面的Text
构建而成
protected override Geometry DefiningGeometry
{
get
{
var formattedText = new FormattedText(Text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Verdana"), 14, Brushes.Transparent);
var chosenTextPoint = new Point
{
X = ((Location.X < BottomRight.X) ? Location.X : BottomRight.X) + 5,
Y = ((Location.Y < BottomRight.Y) ? Location.Y : BottomRight.Y) + 5
};
Stroke = Brushes.ForestGreen;
StrokeThickness = (IsSelected) ? HighlightedValue : HighlightedValue / 2;
Rectangle = new Rect(Location, BottomRight);
var rectangleGeometry = new RectangleGeometry(Rectangle);
var textGeometry = formattedText.BuildGeometry(chosenTextPoint);
var combinedGeometry = new CombinedGeometry
{
GeometryCombineMode = GeometryCombineMode.Xor,
Geometry1 = rectangleGeometry,
Geometry2 = textGeometry
};
combinedGeometry.Geometry1.SetValue(FillProperty, Brushes.Blue);
combinedGeometry.Geometry1.InvalidateProperty(FillProperty);
Fill = (IsSelected) ? Brushes.Transparent : null;
return combinedGeometry;
}
}
combinedGeometry
是我最近添加的东西,在此之前我使用了PathGeometry
。在这两种情况下,Rectangle
和Text
都以相同的颜色着色,并"遭受"相同的形状效果。
我有办法把两者分开吗?通过分离,我的意思是它们都将是Shape
中的单独元素,我可以自由地修改它们中的任何一个,或者将它们全部修改在一起?
Geometry
没有颜色——这正是它的名字所暗示的。Shape
s使用填充笔刷和笔划笔刷绘制单个几何体。
您可以:
- 使用多个形状。这可能代价高昂,因为每个
Shape
都是一个可以接受输入、呈现等的完整控件 - 使用
Drawing
,它可以包含具有多个笔刷的多个几何体,然后使用Image
控件中的DrawingImage
(ImageSource
的类型)或DrawingBrush
(Brush
的类型)作为其他控件(例如Rectangle
)的填充/背景进行渲染。请注意,Blend(Visual Studio附带的工具)可以将一组控件转换为DrawingBrush
("工具">"生成笔刷") - 从头开始创建一个控件,继承自
FrameworkElement
,并通过重写OnRender
来自己呈现它