使用 GDI+在WPF应用程序中
我正在 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 控件
I'm writing a program in WPF application that simulates the game of life.
How can I preform GDI+ like graphics operations to create an Image that contains the grid of cells?
(Normally, in WinForms, I would have know how to do this operation).
Edit:
I used this code:
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;
Background is a System.Windows.Controls.Image
Control
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 WriteableBitmap 或使用一个 WPF 容器,例如其中包含许多矩形的 Grid 或 Canvas。很大程度上取决于游戏板的大小。 WriteableBitmap 可能更适合大型地图,而画布或网格可能更适合较小的尺寸。
这是您要找的吗?
You could use a WriteableBitmap or use a WPF container such as a Grid or Canvas with a lot of rectangles in it. A lot depends on the size of the gameboard. A WriteableBitmap might be better suited for a huge map and a canvas or grid might be easier for smaller sizes.
Is this what you are looking for?
我认为使用 WriteableBitmap.WritePixel 让事情变得更加困难。使用 Shapes 或使用 RendterTargetBitmap 和 DeviceContext 进行绘图会更轻松。
以下是一些有关如何使用此方法进行绘图的代码。
MainForm 的 XAML:
MainForm 的代码隐藏:
根据需要调整图像的宽度/高度。所有绘图逻辑都应该位于 using 语句内。您会发现 DrawingContext 上的方法比 WritePixel 更灵活且更容易理解。每当您想触发重绘时,请调用“DrawStuff”。
I think you're making things harder on yourself by using WriteableBitmap.WritePixel. You'll have a much better time drawing with Shapes or using RendterTargetBitmap and a DeviceContext.
Here's some code on how you would draw using this method.
MainForm's XAML:
MainForm's Code-Behind:
Adjust the Width/Height of the Image to whatever you desire. All of your drawing logic should be inside of the using statement. You'll find the methods on DrawingContext are much more flexible and easier to understand than WritePixel. Call "DrawStuff" whenever you want to trigger a redraw.