【问题标题】:using GDI+ in WPF application在 WPF 应用程序中使用 GDI+
【发布时间】:2011-03-03 15:15:16
【问题描述】:

我正在 WPF 应用程序中编写一个模拟生活游戏的程序。 如何执行类似 GDI+ 的图形操作以创建包含单元格网格的图像?

(通常,在 WinForms 中,我会知道如何执行此操作)。

编辑: 我使用了这段代码:

            WriteableBitmap wb = new WriteableBitmap(width * 5, height * 5, 100, 100, new PixelFormat(), new BitmapPalette(new List<Color> { Color.FromArgb(255, 255, 0, 0) }));
        wb.WritePixels(new Int32Rect(0, 0, 5, 5), new IntPtr(), 3, 3);
        Background.Source = wb;

背景是System.Windows.Controls.Image 控件

【问题讨论】:

  • 您是否想过使用 WPF GridRectangles?您甚至可以获得更好的性能,因为一切都是基于矢量的

标签: wpf gdi+


【解决方案1】:

您可以使用 WriteableBitmap 或使用 WPF 容器,例如 Grid 或 Canvas,其中包含许多矩形。很大程度上取决于游戏板的大小。 WriteableBitmap 可能更适合大型地图,而画布或网格可能更适合较小的尺寸。

Is this what you are looking for?

【讨论】:

【解决方案2】:

我认为您正在使用 WriteableBitmap.WritePixel 让自己变得更难。使用 Shapes 或使用 RendterTargetBitmap 和 DeviceContext 进行绘图会更好。

这里有一些关于如何使用此方法进行绘制的代码。

MainForm 的 XAML:

<Grid>
    <Image Name="Background"
           Width="200"
           Height="200"
           VerticalAlignment="Center"
           HorizontalAlignment="Center" />
</Grid>

MainForm 的代码隐藏:

private RenderTargetBitmap buffer;
private DrawingVisual drawingVisual = new DrawingVisual();

public MainWindow()
{
    InitializeComponent();            
}

protected override void OnRender(DrawingContext drawingContext)
{
    base.OnRender(drawingContext);
    buffer = new RenderTargetBitmap((int)Background.Width, (int)Background.Height, 96, 96, PixelFormats.Pbgra32);
    Background.Source = buffer;
    DrawStuff();
}

private void DrawStuff()
{
    if (buffer == null)
        return;

    using (DrawingContext drawingContext = drawingVisual.RenderOpen())
    {
        drawingContext.DrawRectangle(new SolidColorBrush(Colors.Red), null, new Rect(0, 0, 10, 10));
    }

    buffer.Render(drawingVisual);
}

将图像的宽度/高度调整为您想要的任何值。您所有的绘图逻辑都应该在 using 语句中。您会发现 DrawingContext 上的方法比 WritePixel 更灵活、更易于理解。每当你想触发重绘时调用“DrawStuff”。

【讨论】:

  • 谢谢 :) 看起来很棒。我会在第二天早上检查它(以色列现在是 23:50),除了睡觉什么都不懂..
猜你喜欢
  • 2013-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-07
  • 1970-01-01
  • 1970-01-01
  • 2016-01-29
  • 1970-01-01
相关资源
最近更新 更多