So I was doing this in WinForms .NET 3.5… I am now using WPF .NET 4.0… and I cant figure out how to do it.
This is what I was doing in 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();
}
The above code took the existing image at “input.png”, created a new image from it, wrote text from it and then saved the new image at “output.png”. Text was written using the following function:
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);
}
}
However, since System.Drawing does not exist in WPF .NET 4.0, I can’t use these functions anymore. How would I do what I am trying to do in WPF .NET 4.0? I’ve gotten as far as the code below in order to do the first step of making an image based on the old image:
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);
}
Having read answers and comments here I thought you might appreciate a more comprehensive solution. Here is a little method that does the job:
You would use this method with a FormattedText object and a position:
EDIT: If you want to draw the text horizontally and vertically aligned relative to a certain rectangle, you might replace the
positionparameter by that rectangle and two alignment parameters and calculate the text position like this:Now you might use the method like this: