使用以下代码我在DrawingVisual
上绘图,然后使用Image
将其渲染为RenderTargetBitmap
。最终的Image
稍后会添加到Canvas
并显示在屏幕上。
我的问题在于pixelWidth
方法想要的pixelHeight
和RenderTargetBitmap
个参数。我应该给予什么价值?我注意到如果我给它较低的数字部分图像不会被渲染。我应该在什么基础上选择这些?我在下面的代码中给了它1000。
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;
}
}
答案 0 :(得分:3)
您可以查询DrawingVisual的ContentBounds
属性,
获取ContainerVisual
内容的边界框
或DescendantBounds
属性
获取所有内容的所有内容边界框的并集 ContainerVisual的后代,但不包括的内容 ContainerVisual。
这样的事情应该有效:
var bounds = drawingVisual.DescendantBounds;
var bmp = new RenderTargetBitmap(
(int)Math.Ceiling(bounds.Width), (int)Math.Ceiling(bounds.Height),
96, 96, PixelFormats.Pbgra32);