开发者

Rendering WPF Visual Object as Image Yields Solid Black Image

In a C#/WPF application, I have a DataChart object that I need to save to an image. Currently, the object is added to a Fixed Document and correctly displays on that Fixed Document by using the following code:

VisualBrush chartBrush = new VisualBrush(chart);
Rectangle chartRect = new Rectangle();
chartRect.Height = chartClone.Height;
chartRect.Width = chartClone.Width;
chartRect.Fill = chartBrush;
AddBlockUIElement(chartRect, textAlignment);

However, rather than add it as a block to a Fixed Document, I now need to simply save the image to disk. I've tried doing the following:

RenderTargetBitmap bmp = new RenderTargetBitmap((int)chart.Width, (int)chart.Height, 96, 96, PixelFormats.Default);
bmp.Render(chart);
PngBitmapEncoder image = new PngBitmapEncoder();
image.Frames.Add(BitmapFrame.Create(bmp));
using (Stream fs = File.Create("TestImage.png"))
{
  image.Save(fs);
  fs.Close();
}

However, this simply gives me a solid black image in the size of my chart and I cannot figure out why.

So my question is, does anyone know of a better way to turn the DataChart object into a PNG or BMP image I can save? I've tried searching on getting from a VisualBrush or a Rectangle to an image, but haven't fou开发者_如何学JAVAnd anything, other than the above, that seems to do what I need.

Thanks so much!


See if you can work with the code below:

VisualBrush target = new VisualBrush(element);
DrawingVisual visual = new DrawingVisual();
DrawingContext dc = visual.RenderOpen();
dc.DrawRectangle(target, null, new Rect(0, 0, 
    width, 
    height));
dc.Close();

RenderTargetBitmap bmp = new RenderTargetBitmap(
    (int)width,
    (int)height, 96, 96, PixelFormats.Pbgra32);
bmp.Render(visual); 


replace this line

image.Frames.Add(BitmapFrame.Create(BitmapRender));

with such

image.Frames.Add(BitmapFrame.Create(bmp));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜