I have the following extension method in my application. It captures previews of my usercontrols and allows the user to navigate them via a menu.
/// <summary>/// Renders a framework element as a bitmap image./// </summary>/// <param name="frameworkElement">The framework element to be rendered.</param>/// <param name="background">The background to be applied to the element, in case the element has trasnparent background.</param>/// <param name="scale">The scaling of the image, default should be 1.</param>/// <returns>The image as a scaled bitmap.</returns>public static BitmapImage RenderToBitmap(this FrameworkElement frameworkElement, Brush background, double scale = 1){ Check.NotNull(frameworkElement, "frameworkElement"); // as seen here: http://stackoverflow.com/questions/19395105/wpf-pngbitmapencoder-how-to-disable-background-transparency var renderWidth = (int)(frameworkElement.RenderSize.Width * scale); var renderHeight = (int)(frameworkElement.RenderSize.Height * scale); if (renderWidth > 0 && renderHeight > 0) { var renderTarget = new RenderTargetBitmap(renderWidth, renderHeight, 96, 96, PixelFormats.Default); var sourceBrush = new VisualBrush(frameworkElement); var drawingVisual = new DrawingVisual(); var rect = new Rect(new Point(0, 0), new Point(frameworkElement.RenderSize.Width, frameworkElement.RenderSize.Height)); using (var drawingContext = drawingVisual.RenderOpen()) { drawingContext.PushTransform(new ScaleTransform(scale, scale)); drawingContext.DrawRectangle(background, null, rect); drawingContext.DrawRectangle(sourceBrush, null, rect); } renderTarget.Render(drawingVisual); var image = new BitmapImage(); using (MemoryStream memoryStream = new MemoryStream()) { JpegBitmapEncoder encoder = new JpegBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(renderTarget)); encoder.Save(memoryStream); image.BeginInit(); image.StreamSource = new MemoryStream(memoryStream.ToArray()); image.EndInit(); } return image; } return null;}
Lately we've started a new development with the radmap control and we started to have some issues. The app hanged whenever we entered the view containing the map. I profiled the app and the results tell me that there's an issue with the radmap control.
I've started trying stuff and I realized that the problem starts when I try to generate the visual before the image creation. If I instead do renderTarget.Render(frameworkElement) it seems to work, but then I can't apply the background transformation to the visual. The problem starts when I use the map to create a VisualBrush. Could this be a bug?
Thanks for your time.
