Ancho y Alto de la Imagen en RenderTargetBitmap en WPF
-
02-01-2020 - |
Pregunta
Usando el siguiente código en el que estoy dibujando DrawingVisual
luego renderizándolo a un Image
usando RenderTargetBitmap
.El final Image
posteriormente se añade a un Canvas
y se muestra en la pantalla.
Mi problema es con el pixelWidth
y pixelHeight
argumentos el RenderTargetBitmap
el método quiere.¿Qué valor debería darle?He notado que si le doy números más bajos, partes de la imagen no se representan.¿Sobre qué base debería elegirlos?Le he dado 1000 en el siguiente código.
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;
}
}
Solución
Puede consultar el DrawingVisual ContentBounds
propiedad, que
obtiene el cuadro delimitador para el contenido de ContainerVisual
o el DescendantBounds
propiedad que
Obtiene la unión de todos los cuadros delimitadores de contenido para todos los descendientes del contenedores, pero no incluye el contenido del contenedor.
Algo como esto debería funcionar:
var bounds = drawingVisual.DescendantBounds;
var bmp = new RenderTargetBitmap(
(int)Math.Ceiling(bounds.Width), (int)Math.Ceiling(bounds.Height),
96, 96, PixelFormats.Pbgra32);