首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在WPF中使用GDI +绘图?

在WPF中使用GDI+绘图,可以通过以下步骤实现:

  1. 添加GDI+相关的命名空间
代码语言:csharp
复制
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Media.Imaging;
  1. 创建一个System.Drawing.Graphics对象,用于绘制图形
代码语言:csharp
复制
Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
Graphics graphics = Graphics.FromImage(bitmap);
  1. 使用System.Drawing.Graphics对象进行绘图
代码语言:csharp
复制
graphics.Clear(Color.White);
graphics.DrawString("Hello, GDI+ in WPF!", new Font("Arial", 20), new SolidBrush(Color.Black), new PointF(50, 50));
  1. 将System.Drawing.Bitmap对象转换为System.Windows.Media.Imaging.BitmapSource对象,以便在WPF中显示
代码语言:csharp
复制
MemoryStream memoryStream = new MemoryStream();
bitmap.Save(memoryStream, ImageFormat.Png);
memoryStream.Position = 0;
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memoryStream;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
bitmapImage.Freeze();
  1. 将System.Windows.Media.Imaging.BitmapSource对象设置为WPF控件的Source属性
代码语言:csharp
复制
image.Source = bitmapImage;

完整的示例代码如下:

代码语言:csharp
复制
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows;
using System.Windows.Media.Imaging;

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            int width = 800;
            int height = 600;

            Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            Graphics graphics = Graphics.FromImage(bitmap);

            graphics.Clear(Color.White);
            graphics.DrawString("Hello, GDI+ in WPF!", new Font("Arial", 20), new SolidBrush(Color.Black), new PointF(50, 50));

            MemoryStream memoryStream = new MemoryStream();
            bitmap.Save(memoryStream, ImageFormat.Png);
            memoryStream.Position = 0;

            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = memoryStream;
            bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
            bitmapImage.EndInit();
            bitmapImage.Freeze();

            image.Source = bitmapImage;
        }
    }
}

在这个示例中,我们创建了一个800x600像素的位图,并在其上绘制了一个文本字符串。然后,我们将位图转换为BitmapSource对象,并将其设置为Image控件的Source属性,以便在WPF中显示。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券