所以我在 WinForms .NET 3.5 中执行此操作……我现在正在使用 WPF .NET 4.0……但我不知道该怎么做。
这就是我在 Windows .NET 3.5 中所做的
using (Bitmap eventImg = new Bitmap("input.png"))
{
Graphics eventGfx = Graphics.FromImage(eventImg);
buildText(eventGfx, this.event1.Text);
eventImg.Save("output.png", ImageFormat.Png);
eventGfx.Dispose();
}
上面的代码在“input.png”中获取现有图像,从中创建一个新图像,从中写入文本,然后将新图像保存在“output.png”中。文本是使用以下函数编写的:
private void buildText(Graphics graphic, string text)
{
if (text.Length == 0) { return; }
FontStyle weight = FontStyle.Regular;
switch (this.font_style)
{
case "regular": weight = FontStyle.Regular; break;
case "bold": weight = FontStyle.Bold; break;
case "italic": weight = FontStyle.Italic; break;
case "underline": weight = FontStyle.Underline; break;
case "strikeout": weight = FontStyle.Strikeout; break;
}
using (Font font = new Font(this.font_family, this.font_size, weight, GraphicsUnit.Pixel))
{
Rectangle rect = new Rectangle(this.left, this.top, this.width, this.height);
Brush brush = new SolidBrush(Color.FromArgb(this.font_color));
StringFormat format = new StringFormat();
switch (this.align_x)
{
case "left": format.Alignment = StringAlignment.Near; break;
case "right": format.Alignment = StringAlignment.Far; break;
default: format.Alignment = StringAlignment.Center; break;
}
switch (this.align_y)
{
case "top": format.LineAlignment = StringAlignment.Near; break;
case "bottom": format.LineAlignment = StringAlignment.Far; break;
default: format.LineAlignment = StringAlignment.Center; break;
}
graphic.TextRenderingHint = TextRenderingHint.AntiAlias;
graphic.DrawString(text, font, brush, rect, format);
}
}
但是,由于 WPF .NET 4.0 中不存在 System.Drawing,所以我不能再使用这些函数了。我将如何在 WPF .NET 4.0 中做我想做的事情?为了完成基于旧图像制作图像的第一步,我已经了解了下面的代码:
using (var fileStream = new FileStream(@"z:\ouput.png", FileMode.Create))
{
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(new Uri(@"z:\input.png")));
encoder.Save(fileStream);
}