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();
    }
}
相关推荐
necessary6531 天前
从工行“余额归零”事件看CAP定理:当金融系统在一致性与可用性之间做出选择
分布式·金融·wpf·可用性测试
棉晗榜1 天前
WPF隐藏控件后,怎么让其上部的控件空间自动撑高
wpf
壹佰大多2 天前
【Redisson分布式锁源码分析-3】
数据结构·分布式·mysql·spring·spring cloud·wpf·lua
LateFrames2 天前
以小白视角尝试 WPF / WinUI3 / MAUI / MAUI Blazor 构建 Windows 桌面程序
windows·wpf·maui·mauiblazor·winui3
偶尔的鼠标人3 天前
Avalonia/WPF 打开子窗口,并且跨页面传值
c#·wpf·mvvm·avalonia
玖笙&3 天前
✨WPF编程进阶【6.1】:图形原则(附源码)
c++·c#·wpf·visual studio
lixy5793 天前
WPF检测网络状态切换
wpf
纸照片3 天前
WPF中为Button设置IsMouseOver和IsPressed事件中改变背景颜色不起作用
c#·.net·wpf
Aevget3 天前
DevExpress WPF中文教程:Data Grid - 如何使用虚拟源?(四)
ui·.net·wpf·devexpress·wpf控件
Z_W_H_3 天前
【ArcGISProSDK】刷新按钮样式
wpf·arcgisprosdk