Using RenderTargetBitmap with a Viewport3D - wpf

I use Viewport3d and display my 3D Elements with inherited UIElement3D classes... Now I want to make different images of my viewport (different views). That means I have to make a new viewport3d at runtime and apply my specific view for the image on it..
see the following code:
' Start creating Image
Dim bitmap As New RenderTargetBitmap(800,
800,
96,
96,
PixelFormats.Default)
'--------------------
'Render xamlViewport works perfect
bitmap.Render(xamlViewport)
Using stream As FileStream = New FileStream("C:\\temp\\test_xamlviewport.png", FileMode.Create)
Dim encoder As New PngBitmapEncoder
encoder.Frames.Add(BitmapFrame.Create(bitmap))
encoder.Save(stream)
End Using
'---------------------
'Render local Viewport don't work
Dim oViewport As New Viewport3D
oViewport.Height = 800
oViewport.Width = 800
oViewport.Children.Add(New C3DCuboid())
oViewport.Camera = New PerspectiveCamera(New Point3D(4, 7, 6), New Vector3D(-4, -7, -6), New Vector3D(0, 1, 0), 45)
Dim oVisual As New ModelVisual3D
oVisual.Content = New DirectionalLight(Colors.White, New Vector3D(-1, -2, -3))
oViewport.Children.Add(oVisual)
oViewport.Measure(New Size(800, 800))
oViewport.Arrange(New Rect(New Size(800, 800)))
bitmap = New RenderTargetBitmap(800,
800,
96,
96,
PixelFormats.Default)
bitmap.Render(oViewport)
Using stream As FileStream = New FileStream("C:\\temp\\test_localviewport.png", FileMode.Create)
Dim encoder As New PngBitmapEncoder
encoder.Frames.Add(BitmapFrame.Create(bitmap))
encoder.Save(stream)
End Using
The first picture (test_xamlviewport.png) is shown correctly, but the second picture where I create my own Viewport3D Object and print it is empty (test_localviewport.png).
How can I force to Render my UIElement3D Objects or why it doesn't work if i make a new Viewport vs print the existing XAML viewport instance?
Here you find a sample solution which reproduce my problem
http://cid-df67ca3f85229bd1.office.live.com/self.aspx/Development/WpfApplication2.zip
Regards
Roland

Related

How can I draw a Polyline onto an Image (WPF)

I've tried a few different approaches to this, but can't seem to get a combination that works.
Creating WPF app in C#, Visual Studio.
System.Windows.Shapes.Polyline works really nicely to draw into a Canvas in real-time, but I want to be able to draw in higher resolution onto a non-visual component that I can then render onto an Image.
If I create a Polyline on a Canvas that's visible in the UI, this works fine:
// Make rendertarget size of full page
RenderTargetBitmap rtb = new RenderTargetBitmap((int)wPage, (int)hPage, 96, 96, PixelFormats.Default);
// Render the polyline
rtb.Render(lineVirt);
// Apply to background image
imgBG.Source = rtb;
But if I create a Polyline on a Canvas that's not visible in the UI, then nothing renders to the image. This is probably fair enough. My guess is that the component recognises that it's not visible and therefore doesn't bother to render.
I've considered putting the Canvas somewhere in the UI buried under other controls, but that seems like a horrible kind of hack.
Essentially, all I need is a clean and fast way to draw a multi-point line of a specified width and color onto an Image. I thought that Polyline would work well, but only seems to work in a visible container.
What are my options?
You do not need a rendered Canvas or any other visible Panel at all.
Just use basic drawing primitives available at the Visual layer.
The DrawGeometry method below draws a Geometry onto a BitmapSource, using the bitmap's rendered size, i.e. the size that takes its DPI into account, and returns the resulting BitmapSource.
public static BitmapSource DrawGeometry(
BitmapSource source, Pen pen, Geometry geometry)
{
var visual = new DrawingVisual();
var rect = new Rect(0, 0, source.Width, source.Height);
using (var dc = visual.RenderOpen())
{
dc.DrawImage(source, rect);
dc.DrawGeometry(null, pen, geometry);
}
var target = new RenderTargetBitmap(
(int)rect.Width, (int)rect.Height, 96, 96, PixelFormats.Default);
target.Render(visual);
return target;
}
In order to draw in the bitmap's pixel units and hence ignore its DPI, modify the method like this:
var rect = new Rect(0, 0, source.PixelWidth, source.PixelHeight);
using (var dc = visual.RenderOpen())
{
dc.DrawRectangle(new ImageBrush(source), null, rect);
dc.DrawGeometry(null, pen, geometry);
}
The following method uses the above to draw a polyline as an IEnumerable<Point>.
public static BitmapSource DrawPolyline(
BitmapSource source, Pen pen, IEnumerable<Point> points)
{
var geometry = new PathGeometry();
if (points.Count() >= 2)
{
var figure = new PathFigure { StartPoint = points.First() };
figure.Segments.Add(new PolyLineSegment(points.Skip(1), true));
geometry.Figures.Add(figure);
}
return DrawGeometry(source, pen, geometry);
}
It would be used like
var source = new BitmapImage(new Uri(...));
var pen = new Pen
{
Brush = Brushes.Blue,
Thickness = 2,
};
var points = new List<Point>
{
new Point(100, 100),
new Point(1000, 100),
new Point(1000, 1000),
new Point(100, 1000),
new Point(100, 100),
};
image.Source = DrawPolyline(source, pen, points);
Your canvas needs a size, so someone or something has to Arrange it. That might already be enough to get it to render, but the only reliable way of rendering arbitrary visuals to a bitmap is to actually place them in the visual tree of a window that's displayed and thus laid out by WPF. You can then render to the bitmap in a deferred task at ContextIdle priority to ensure that layout is complete.

Save System.Windows.Media.Brush as image file to disk

I have D3DImage _di that use to draw a background of Wpf Border in the form of a Brush.
The Image is rendered fine but i want to save the Brush to png file on disk even if the Brush is not showed on the View.
I tried as below to save it to disk but all i got is black image:
_receivedBrush =(Brush)new ImageBrush((ImageSource)_di)
RenderTargetBitmap bmpCopied = new RenderTargetBitmap(350, 174, 96, 96, PixelFormats.Default);
DrawingVisual dv = new DrawingVisual();
using (DrawingContext dc = dv.RenderOpen())
{
dc.DrawRectangle(_receivedBrush, null, new Rect(new Point(), new Size(350, 174)));
}
bmpCopied.Render(dv);
MemoryStream mse = new MemoryStream();
BmpBitmapEncoder mem = new BmpBitmapEncoder();
mem.Frames.Add(BitmapFrame.Create(bmpCopied));
mem.Save(mse);
File.WriteAllBytes(#"g:\brush.png", mse.ToArray());
mse.Close();
Thanks in advance,
Try changing to PngBitmapEncoder or change the file extension to bmp.

WPF DataGrid GridLines not visible when saved as PDF

I'm using a DataGrid to represent some data in a WPF application. In a feature where I'm saving a particular WPF Window which has the DataGrid into a PDF using PDFSharp, I'm facing an issue that the DataGrid GridLines are not visible when the saved PDF is viewed in smaller viewing percentages.
(Refer attached images, only when the PDF view is set at 139%, the GridLines are visible. However, in smaller viewing %, some grid lines get omitted.)
Here's the PDF Saving Code:-
MemoryStream lMemoryStream = new MemoryStream();
Package package = Package.Open(lMemoryStream, FileMode.Create);
var doc = new System.Windows.Xps.Packaging.XpsDocument(package);
XpsDocumentWriter writer = System.Windows.Xps.Packaging.XpsDocument.CreateXpsDocumentWriter(doc);
VisualBrush sourceBrush = new VisualBrush(this);
DrawingVisual drawingVisual = new DrawingVisual();
using (var drawingContext = drawingVisual.RenderOpen())
{
drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(this.ActualWidth, this.ActualHeight)));
}
writer.Write(drawingVisual);
doc.Close();
package.Close();
var pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(lMemoryStream);
XpsConverter.Convert(pdfXpsDoc, sFileName, 0);
I believe it has to do with the quality with which the visual is drawn. Then I tried this snippet where I'm using DrawImage to make the visual at a higher resolution. Here's the snippet:-
MemoryStream lMemoryStream = new MemoryStream();
Package package = Package.Open(lMemoryStream, FileMode.Create);
var doc = new System.Windows.Xps.Packaging.XpsDocument(package);
XpsDocumentWriter writer = System.Windows.Xps.Packaging.XpsDocument.CreateXpsDocumentWriter(doc);
double dpiScale = 600.0 / 96.0;
var renderBitmap = new RenderTargetBitmap(Convert.ToInt32(this.Width * dpiScale),
Convert.ToInt32(this.Height * dpiScale),
600.0,
600.0,
PixelFormats.Pbgra32);
renderBitmap.Render(this);
var visual = new DrawingVisual();
using (var dc = visual.RenderOpen())
{
dc.DrawImage(renderBitmap, new Rect(0, 0, this.Width, this.Height));
}
writer.Write(visual);
doc.Close();
package.Close();
var pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(lMemoryStream);
XpsConverter.Convert(pdfXpsDoc, _pdfFileName, 0);
This snippet is working as in the grid lines are visible even in smaller viewing percentages but it makes my application stuck at the PDF save operation and also it throws System.OutofMemoryException with message "Insufficient memory to continue the execution of the program." However, the application doesn't crash.
To check the behavior of PDF viewer, I generated a table with multiple rows and columns in MS Word and saved it as a PDF. In that case, the table grid lines are clearly visible even at small viewing percentages.
Can anyone help me with this?
I assume the first code snippet creates a table in vector format (you do not supply a PDF that allows to verify this).
The second code snippet attempts to create a bitmap image (raster format).
Either way: with both vector and raster images it depends on the PDF viewer whether thin lines are visible. Adobe Reader has many options (like "Enhance thin lines", "Smooth line art", "Smooth images") that will have an effect on the actual display - to be set on the client computer, nothing to be set in the PDF.
I assume your test with MS Word also created a table in vector format, but maybe with thicker lines. So this test proofs nothing.
I had the same problem with disappearing grid lines when zooming out a PDF created with WPF.
The problem was that the TextBox objects in the Grid cells had a default background color (white) and a border color (black), and both were painted in the same place when zooming out. The solution was to not have a background at all, by setting the background to Transparent.
TextBox tx = new TextBox();
tx.Text = "X";
tx.SetValue(Grid.RowProperty, row);
tx.SetValue(Grid.ColumnProperty, col);
tx.BorderThickness = new Thickness(0.3, 0.3, 0, 0);
tx.BorderBrush = System.Windows.Media.Brushes.Black;
tx.Background = Brushes.Transparent;
grid.Children.Add(tx);
But what if you want to have some background in the grid cell? Then the solution is to add a separate Border object to the same Grid cell, and use Zindex to make sure that the Border object is painted in front of the other content.
TextBox tx = new TextBox();
tx.Text = "X";
tx.SetValue(Grid.RowProperty, row);
tx.SetValue(Grid.ColumnProperty, col);
tx.BorderThickness = new Thickness(0);
tx.Background = Brushes.LightPink;
grid.Children.Add(tx);
Border ct = new Border();
ct.SetValue(Grid.RowProperty, row);
ct.SetValue(Grid.ColumnProperty, col);
ct.BorderThickness = new Thickness(0.3, 0.3, 0, 0);
ct.BorderBrush = System.Windows.Media.Brushes.Black;
ct.Background = Brushes.Transparent;
ct.HorizontalAlignment = HorizontalAlignment.Stretch;
ct.VerticalAlignment = VerticalAlignment.Stretch;
Grid.SetZIndex(ct, 100);
grid.Children.Add(ct);
Also, UseLayoutRounding must be set to false (false is default). Otherwise lines with Thickness 0.5 or lower will disappear completely.

HowTo determine the Anchor Point of the System.Windows.Media.DrawingContext?

How to determine the Anchor Point of the System.Windows.Media.DrawingContext? exactly like RenderTransformOrigin in Image WPF Control.
Dim InImage As New BitmapImage(New Uri("Image Path"))
Dim DrawingGroup As New DrawingGroup
Dim DrawingContext As DrawingContext = DrawingGroup.Open
DrawingContext.PushTransform(New RotateTransform(53))
DrawingContext.DrawImage(InImage, New Rect(0, 0, 500, 500))
DrawingContext.Close()
I want to Render Image using Several Anchor Points.
I think you mean Anchor Point as the point around which the rotating is performed. So you can set that point right via the RotateTransform. It has a pair of properties namely CenterX and CenterY:
...
Dim Rotating As New RotateTransform(53)
Rotating.CenterX = Some_Value_For_X
Rotating.CenterY = Some_Value_For_Y
DrawingContext.PushTransform(Rotating)
...

VisualBrush size and stretch problems

I would like to export a grid (whit all his children) to a PNG.
The problem is that some of these children are outside of the grid.
Here is my code:
VisualBrush sourceBrush = new VisualBrush(MyGrid);
DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext drawingContext = drawingVisual.RenderOpen())
{
drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(Math.Floor(exportWidth), Math.Floor(exportHeight))));
drawingContext.Close();
}
RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)Math.Floor(exportWidth), (int)Math.Floor(exportHeight), 96, 96, PixelFormats.Default);
renderTarget.Render(drawingVisual);
The resulting image is blurred if at least one of the children is outside the grid.
The exportHeight and exportWidth values are calculated upstream, relative to the position of the grid's children.
If all children are inside the grid, the picture is clear.
I think this is because of the VisualBrush original size that cannot be changed.
Do you know a way to fix it ?
EDIT :
I do not call renderTarget.Render(MyGrid); because it does not take in charge children who are outside the grid (Children whose top or left value is negative).
Have you tried?
MyGrid.ClipToBounds = true;

Resources