[翻译]XNA外文博客文章精选之seven


PS:自己翻译的,转载请著明出处

                                                    加载一个XNA纹理到一个GDI+图象中
                                  这里是一个小功能去加载一个32bit图象到GDI+中,这是非常有用的当你使用WinForms为你的游戏写一个工具。

1 public class XNAGDIImageLoader
                                  因为GDI+将要求我们去操作一个指针在内存中,我们将使用这个功能的不安全模式。
                                  我们需要传入到窗口处理中,为了在内存中创建XNA设备。
1 public unsafe static Image LoadImage(string fileName,IntPtr windowHandle)
                                  参看前面的教程在内存中创建一个设备。
1 GraphicsDevice dev = XNADevice.GetDevice(windowHandle);

                                  现在,我们有了这个设备,我们可以使用XNA去加载一个纹理。

1 Texture2D tex = Texture2D.FromFile(dev, fileName);
                                  让我们分配空间去保存纹理的bits.
1 Color[] d = new Color[tex.Width * tex.Height];
                                  现在,我们移动实际的纹理bits到我们分配的内存中
1 tex.GetData<Color>(d);
                                  现在是时候去创建GDI+的位图了。此时因为我们只支持32bit,我们将创建一个与纹理同样高宽的32bit的图象。
1 Bitmap bmp = new Bitmap(tex.Width,tex.Height,System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                                  为了从内存中的GDI+图象读取bits,我们需要锁住位图。
1 System.Drawing.Imaging.BitmapData bmpd = bmp.LockBits(new System.Drawing.Rectangle(00, bmp.Width, bmp.Height),System.Drawing.Imaging.ImageLockMode.WriteOnly,System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                                  让我们得到一个指针到这个象素bits并且复制XNA纹理的bits。XNA提供一个属性去返回一个不安全的整型从纹理的颜色值:PackedValue
1 uint* ptr = (uint*)bmpd.Scan0.ToPointer();
2 for (int x = 0; x < tex.Width; x++)
3     for (int y = 0; y < tex.Height; y++)
4     {
5          ptr[x + y * tex.Width] = d[x + y * tex.Width].PackedValue;
6     }
                                  不要忘记清除GDI+和XNA图象。
1 bmp.UnlockBits(bmpd);
2 dev.Dispose();
                                  最后我们从位图中创建图象。
1 return Image.FromHbitmap(bmp.GetHbitmap());
源代码:http://www.ziggyware.com/readarticle.php?article_id=57
(完)
原文地址:https://www.cnblogs.com/315358525/p/1562021.html