繁体   English   中英

c#wpf多边形到位图不显示任何内容

[英]c# wpf polygon to bitmap not displaying anything

抱歉,如果您认为此问题已得到回答,那么我确实到处都在试图找出执行此操作的结果,但它没有显示任何内容。 这是我的全部代码:

Polygon hexagon = new Polygon();
PointCollection pc = new PointCollection();
double side = 25;
double xOffset = 0, yOffset = 0;
double r = System.Math.Cos((System.Math.PI / 180) * 30) * side;
double h = System.Math.Sin((System.Math.PI / 180) * 30) * side;

//Create the 6 points needed to create a hexagon
pc.Add(new Point(xOffset, yOffset)); //Point 1
pc.Add(new Point(xOffset + side, yOffset)); //Point 2
pc.Add(new Point(xOffset + side + h, yOffset + r)); //Point 3
pc.Add(new Point(xOffset + side, yOffset + 2 * r)); //Point 4
pc.Add(new Point(xOffset, yOffset + 2 * r)); //Point 5
pc.Add(new Point(xOffset - h, yOffset + r)); //Point 6

hexagon.Stroke = Brushes.Blue;
hexagon.StrokeThickness = 1;
hexagon.Fill = Brushes.LightBlue;
hexagon.Points = pc;

RenderTargetBitmap bmp = new RenderTargetBitmap(200, 200, 96, 96, PixelFormats.Default);
bmp.Render(hexagon);
img.Source = bmp;

我创建了一个六边形作为多边形对象,并使用RenderTargetBitmap尝试将多边形转换为位图,但似乎没有显示任何可见的内容。 我还添加了一个画布,并在其中添加了Polygon对象,这似乎可行。 只是在转换为位图时。 我确实对代码中的错误感到迷茫。 我现在在主窗口已加载事件中拥有所有内容。

帮助将不胜感激,谢谢。

解决方案可能很简单,或者我忽略了一些,希望解决方案很简单:)。

WPF UIElement必须先布局才能可见。 它必须至少获得一个Measure and Arrange调用,并在其中获得一个可用的Size和一个最后的Rect Rect(通常从其父面板)。 在将新创建的元素渲染到RenderTargetBitmap中时,您将使用适当的Size和Rect值手动调用这些方法:

...
hexagon.Measure(new Size(200, 200)); // adjust this to your needs
hexagon.Arrange(new Rect(0, 0, 200, 200)); // adjust this to your needs

var bmp = new RenderTargetBitmap(200, 200, 96, 96, PixelFormats.Default);
bmp.Render(hexagon);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM