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();
    }
}
相关推荐
十月南城3 天前
Flink实时计算心智模型——流、窗口、水位线、状态与Checkpoint的协作
大数据·flink·wpf
听麟5 天前
HarmonyOS 6.0+ 跨端会议助手APP开发实战:多设备接续与智能纪要全流程落地
分布式·深度学习·华为·区块链·wpf·harmonyos
@hdd5 天前
Kubernetes 可观测性:Prometheus 监控、日志采集与告警
云原生·kubernetes·wpf·prometheus
zls3653655 天前
C# WPF canvas中绘制缺陷分布map
开发语言·c#·wpf
专注VB编程开发20年6 天前
c#Redis扣款锁的设计,多用户,多台电脑操作
wpf
闲人编程6 天前
定时任务与周期性调度
分布式·python·wpf·调度·cron·定时人物·周期性
zls3653656 天前
C# WPF canvas中绘制缺陷分布map并实现缩放
开发语言·c#·wpf
数据知道8 天前
PostgreSQL:Citus 分布式拓展,水平分片,支持海量数据与高并发
分布式·postgresql·wpf
闲人编程8 天前
Redis分布式锁实现
redis·分布式·wpf·进程··死锁·readlock
之歆8 天前
ZooKeeper 分布式协调服务完全指南
分布式·zookeeper·wpf