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();
    }
}
相关推荐
code bean1 天前
【WPF】WPF 自定义控件之依赖属性
wpf
上元星如雨1 天前
WPF 加载和显示 GIF 图片的完整指南
wpf
微小冷2 天前
WPF中ListView控件详解
c#·wpf·数据绑定·listview·bingding
专注VB编程开发20年3 天前
WPF,Winform,HTML5网页,哪个UI开发速度最快?
大数据·c#·wpf
YANQ6623 天前
3.1 WPF画折线图、直方图、饼状图
wpf
上元星如雨3 天前
WPF demo:全屏加载界面
wpf
深漂阿碉3 天前
WPF自定义日历选择控件
wpf
六点的晨曦3 天前
WPF的三轴机械手控件动画
wpf
军训猫猫头3 天前
5.浏览本地文件获取路径与文件名称 C#例子 WPF例子
开发语言·c#·wpf
步、步、为营4 天前
.NET + WPF框架开发聊天、网盘、信息发布、视频播放功能
.net·wpf·音视频