好了,问题很简单,我在WPF Visual上渲染了一些东西。我想把它放在DirectX Texture上。目前,我使用以下代码来完成工作。

var bmp = new System.Windows.Media.Imaging.RenderTargetBitmap(bound.Width, bound.Height, 96, 96, System.Windows.Media.PixelFormats.Pbgra32);
bmp.Render(drawingVisual);
var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bmp));
Texture texture = new Texture(dxDevice, bound.Width, bound.Height, 1, Usage.RenderTarget, Format.A8R8G8B8, Pool.Default);
using (MemoryStream ms = new MemoryStream())
{
    encoder.Save(ms);
    ms.Seek(0, SeekOrigin.Begin);
    Surface privateSurface = texture.GetSurfaceLevel(0);
    SurfaceLoader.FromStream(privateSurface, ms, Filter.None, Color.MediumAquamarine.ToArgb());
    ms.Close();
}
return texture; // our prepared texture


但这显然很慢。你们能建议一些可能更快的方法吗?

[编辑]我尝试使用CopyPixels()加载数据,但它引发D3DXERR_INVALIDDATA异常。

RenderTargetBitmap bmp = GetBitmap();
// copy into a byte array
int stride = bmp.PixelWidth * 4;
byte[] data = new byte[bmp.PixelHeight * stride];
bmp.CopyPixels(data, stride, 0);

// create texture
using (MemoryStream ms = new MemoryStream(data))
{
    ms.Seek(0, SeekOrigin.Begin);

    if (dxDevice != null)
    {
        // next line throws D3DXERR_INVALIDDATA exception
        texture = TextureLoader.FromStream(dxDevice, ms);
    }
}


[编辑]好的,这就是我设法做到的方式。

RenderTargetBitmap bmp = GetBitmap();
// copy into a byte array
int stride = bmp.PixelWidth * 4;
byte[] data = new byte[bmp.PixelHeight * stride];
bmp.CopyPixels(data, stride, 0);

// create texture
Texture texture = new Texture(dxDevice, bound.Width, bound.Height, 1, Usage.SoftwareProcessing, Format.A8R8G8B8, Pool.Managed);
Surface privateSurface = texture.GetSurfaceLevel(0);
var graphicsStream = privateSurface.LockRectangle(LockFlags.None);
graphicsStream.Write(data);
privateSurface.UnlockRectangle();

最佳答案

是。您仍然可以使用RenderTargetBitmap。但是,您可以在CopyPixels上调用RenderTargetBitmap,然后将像素直接写入纹理中,而不是将其编码为PNG并在Direct3D中读取。应该快得多!

// render the visual, just like you did
var bmp = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Default, null);
bmp.Render(visual);

// get the pixels
var pixels = new int[width * height];
bmp.CopyPixels(pixels, 4 * width, 0); // each line consists of 4*width bytes.


现在,根据您使用的确切API(SlimDX?还有什么?),您需要锁定纹理,并将pixels数组中的数据写入纹理。

09-30 22:43