I have a Stackpanel inside a Scrollviewer where Canvas elements are inserted in the code behind.
Each Canvas Element has a Image, and some Labels, that can be moved around inside the Canvas. For each Label inside each Canvas i want to create a Png Image. My goal is to insert those Png Images to a existing pdf file later. The problem is that i only get black images.
I have already searched with google and stackoverflow but did not really find an answer.
The labels are added to the Canvas by Code and are not created in xaml. I also tried to create a Png for each Canvas instead of the labels. The image for the first Canvas was created correctly. But the second was black again.
I would be really thankful if someone knows what i am doing wrong.
foreach (Canvas canvas in StackPanel_Canvas_Container.Children)
{
foreach (object o in canvas.Children)
{
if (o.GetType().Equals(typeof(Label)))
{
Label label = (Label)o;
label.Background = Brushes.Transparent;
label.Foreground = Brushes.Black;
label.UpdateLayout();
RenderTargetBitmap bitmap = new RenderTargetBitmap((int)label.ActualWidth, (int)label.ActualHeight, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(label);
String path = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "created_images");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
String tmp = string.Empty;
do
{
tmp = System.IO.Path.Combine(path, $"img_{++i}.png");
} while (File.Exists(tmp));
using (FileStream stream = File.Create(tmp))
{
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
encoder.Save(stream);
}
}
}
}