【问题标题】:c# wpf polygon to bitmap not displaying anythingc# wpf多边形到位图不显示任何东西
【发布时间】:2015-04-22 02:00:09
【问题描述】:

很抱歉,如果您认为这个问题已经得到解答,我确实到处寻找,试图找出当我这样做时,它没有显示任何内容。 这是我所有的代码:

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 对象,这似乎有效。只是在转换为位图时。我真的不知道我的代码有什么问题。我现在在主窗口加载事件中拥有一切。

我们将不胜感激,谢谢。

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

【问题讨论】:

    标签: c# wpf bitmap polygon


    【解决方案1】:

    WPF UIElement 必须在可见之前进行布局。它必须至少获得一个MeasureArrange 调用,在那里它获得一个可用的Size 和一个最终的排列矩形(通常来自其父面板)。当将新创建的元素渲染到 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);
    

    【讨论】:

    • 哇。我记得我遇到过这样的事情,但不确定它是如何使用的,所以我将其驳回。感谢您的帮助:),不胜感激。还在用 c# 学习图形。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多