问题
Using the below code I'm drawing on DrawingVisual
then rendering it to an Image
using RenderTargetBitmap
. The final Image
is later added to a Canvas
and displayed on the screen.
My problem is with the pixelWidth
and pixelHeight
arguments the RenderTargetBitmap
method wants. What valued should I give to it? I have noticed that if I give it lower numbers parts of the image is not rendered. On what basis should I choose these? I have given it 1000 in the code below.
public class ModelBeamSectionNamesInPlan : Image
{
private readonly VisualCollection _visuals;
public ModelBeamSectionNamesInPlan(BaseWorkspace space)
{
var typeface = Settings.BeamTextTypeface;
var cultureinfo = Settings.CultureInfo;
var flowdirection = Settings.FlowDirection;
var beamtextsize = Settings.BeamTextSize;
var beamtextcolor = Settings.InPlanBeamTextColor;
beamtextcolor.Freeze();
const double scale = 0.6;
var drawingVisual = new DrawingVisual();
using (var dc = drawingVisual.RenderOpen())
{
foreach (var beam in Building.ModelBeamsInTheElevation)
{
var text = beam.Section.Id;
var ft = new FormattedText(text, cultureinfo, flowdirection,
typeface, beamtextsize, beamtextcolor,
null, TextFormattingMode.Display)
{
TextAlignment = TextAlignment.Center
};
// Draw Text
dc.DrawText(ft, space.FlipYAxis(x, y));
}
}
var bmp = new RenderTargetBitmap(1000, 1000, 120, 96, PixelFormats.Pbgra32);
bmp.Render(drawingVisual);
Source = bmp;
}
}
回答1:
You can query the DrawingVisual's ContentBounds
property, which
gets the bounding box for the contents of the ContainerVisual
or the DescendantBounds
property which
gets the union of all the content bounding boxes for all of the descendants of the ContainerVisual, but not including the contents of the ContainerVisual.
Something like this should work:
var bounds = drawingVisual.DescendantBounds;
var bmp = new RenderTargetBitmap(
(int)Math.Ceiling(bounds.Width), (int)Math.Ceiling(bounds.Height),
96, 96, PixelFormats.Pbgra32);
来源:https://stackoverflow.com/questions/25081821/width-and-height-of-the-image-in-rendertargetbitmap-in-wpf