在WPF中使用GeometryDrawing绘制文本

时间:2016-07-19 04:28:16

标签: c# wpf

我通常使用基于winform的C#,所以我觉得没有适当的WPF基本概念。你能给我一个简单的建议吗?我如何在这个看起来像矩形区域的GeometryDrawing上画文字?

Brush brush = new SolidColorBrush(Colors.BlueViolet);
brush.Freeze();
Brush penBrush = new SolidColorBrush(Colors.Red);
penBrush.Freeze();
Pen pen = new Pen(penBrush, 0.5);
pen.Freeze();

//draw a square with the created brush and pen
System.Windows.Rect r = new System.Windows.Rect(0, 0, 100, 30);
Geometry g = new RectangleGeometry(r);
GeometryDrawing drawing = new GeometryDrawing(brush, pen, g);

drawing.Freeze();

DrawingImage drawingImage = new DrawingImage(drawing);
drawingImage.Freeze();

_image = new Image();
_image.Source = drawingImage;

1 个答案:

答案 0 :(得分:2)

这是你想要使用的非常低级别的api。通常情况下,有更简单的替代方法可以在表单上放置带有文本的视觉效果,但如果您确定要获得ImageSource,那么就是这样:

var visual = new DrawingVisual();
using (var ctx = visual.RenderOpen())
{

    //rectangle
    ctx.DrawGeometry(brush, pen, r);

    //text
    var text = new FormattedText("Hello world!",
        CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, typeface, 11, Brushes.Black);
    text.MaxTextWidth = r.Rect.Width;
    text.MaxTextHeight = r.Rect.Height;

    ctx.DrawText(text, r.Rect.TopLeft);
}
RenderTargetBitmap rtv = new RenderTargetBitmap(pixelWidth, pixelHeight, 96.0, 96.0, PixelFormats.Default);
rtv.Render(visual);
rtv.Freeze();

_image = new Image();
_image.Source = rtv;