在 directx 和 GDI 之间没有直接的交互方式。当我遇到同样的问题时,我求助于准备好从 GDI 到内存的字节,然后返回到 direct3D。我在下面添加了我的代码,它应该可以工作,因为我认为它正在我的项目中使用:)
请注意,这是针对 directx11(应该很容易转换)。此外,*B*GRA 纹理格式的使用是有意的,否则颜色会反转。
如果您需要更高的性能,我建议您查看 DirectDraw。
private byte[] getBitmapRawBytes(Bitmap bmp)
{
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
System.Drawing.Imaging.BitmapData bmpData =
bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
// Get the address of the first line.
IntPtr ptr = bmpData.Scan0;
// Declare an array to hold the bytes of the bitmap.
int bytes = Math.Abs(bmpData.Stride) * bmp.Height;
byte[] rgbValues = new byte[bytes];
// Copy the RGB values into the array.
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
// Unlock the bits.
bmp.UnlockBits(bmpData);
return rgbValues;
}
/// <summary>
/// The bitmap and the texture should be same size.
/// The Texture format should be B8G8R8A8_UNorm
/// Bitmap pixelformat is read as PixelFormat.Format32bppArgb, so if this is the native format maybe speed is higher?
/// </summary>
/// <param name="bmp"></param>
/// <param name="tex"></param>
public void WriteBitmapToTexture(Bitmap bmp, GPUTexture tex)
{
System.Diagnostics.Debug.Assert(tex.Resource.Description.Format == Format.B8G8R8A8_UNorm);
var bytes = getBitmapRawBytes(bmp);
tex.SetTextureRawData(bytes);
}