WPF中使用DrawingContext绘制文字

可以使用DrawingContext的DrawText方法。这个方法允许您指定要绘制的文字内容、文字格式、文字笔刷(颜色或画笔)等信息。

csharp 复制代码
using System;
using System.Windows;
using System.Windows.Media;

public class MyDrawingVisual : DrawingVisual
{
    public void DrawTextWithFormatting()
    {
        using (DrawingContext drawingContext = RenderOpen())
        {
            // 创建文字格式
            Typeface typeface = new Typeface(new FontFamily("Arial"), FontStyles.Italic, FontWeights.Bold, FontStretches.Normal);
            FormattedText formattedText = new FormattedText(
                "Hello, World!",   // 文字内容
                System.Globalization.CultureInfo.CurrentCulture,
                FlowDirection.LeftToRight,
                typeface,
                36,                 // 文字大小
                Brushes.Black       // 文字笔刷
            );

            // 指定文字的位置
            Point textPosition = new Point(50, 50);

            // 绘制文本
            drawingContext.DrawText(formattedText, textPosition);
        }
    }
}

public class MainWindow : Window
{
    public MainWindow()
    {
        // 创建一个画布
        DrawingVisual drawingVisual = new MyDrawingVisual();

        // 创建主窗口内容
        ((MyDrawingVisual)drawingVisual).DrawTextWithFormatting();

        // 创建一个Image对象,用于显示绘制的图像
        Image imageControl = new Image();

        // 使用DrawingVisual对象创建一个DrawingImage
        DrawingImage drawingImage = new DrawingImage(drawingVisual.Drawing);

        // 将DrawingImage设置为Image控件的源
        imageControl.Source = drawingImage;

        // 将Image添加到主窗口中
        Content = imageControl;
    }
}

// 在这里调用主窗口
public class Program
{
    [STAThread]
    public static void Main(string[] args)
    {
        MainWindow mainWindow = new MainWindow();
        mainWindow.ShowDialog();
    }
}
相关推荐
Macbethad1 天前
使用WPF编写一个多维度伺服系统的程序
大数据·hadoop·wpf
lingxiao168881 天前
WPF Prism框架应用
c#·wpf·prism
Macbethad2 天前
使用WPF编写一个Ethercat主站的程序
wpf
难搞靓仔2 天前
WPF 弹出窗体Popup
wpf·popup
Macbethad2 天前
使用WPF编写一个MODBUSTCP通信的程序
wpf
unicrom_深圳市由你创科技2 天前
Avalonia.WPF 跨平台图表的使用
wpf
-大头.2 天前
深入解析ZooKeeper核心机制
分布式·zookeeper·wpf
Macbethad2 天前
使用WPF编写一个RS232主站程序
wpf
Macbethad2 天前
使用WPF编写一个485通信主站程序
wpf
忧思幽释3 天前
Mariadb Galera集群在Openstack中的应用
wpf·openstack·mariadb