在WPF中使用GDI+绘图,可以通过以下步骤实现:
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Media.Imaging;
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;
完整的示例代码如下:
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中显示。
领取专属 10元无门槛券
手把手带您无忧上云