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();
    }
}
相关推荐
sczmzx9 小时前
Cefsharp.WPF高分辨率下崩溃问题解决方案
wpf
cjp5601 天前
023.WPF combox控件数据绑定
wpf
Scout-leaf1 天前
WPF新手村教程(七)—— 终章(MVVM架构初见杀)
c#·wpf
极客智造1 天前
WPF DataGrid 多选绑定 + 强类型命令回调 通用解决方案
wpf
ZoeJoy81 天前
机器视觉C# 调用相机:从 USB 摄像头到海康工业相机(WinForms & WPF)
数码相机·c#·wpf
ALex_zry2 天前
C++高性能日志与监控系统设计
c++·unity·wpf
zhojiew2 天前
使用flink agent框架实现流式情感分析的示例
大数据·flink·wpf
海盗12342 天前
ScottPlot在WPF的基本使用和中文乱码问题
c#·.net·wpf
俄城杜小帅2 天前
C++线程异步和wpf中比较
java·c++·wpf
ZoeJoy82 天前
WPF 从入门到实践:基础、ModernUI 与 MVVM 完全指南
c#·wpf