我已将C#游戏从OpenTK(OpenGL)转换为SharpDX(DirectX),并已从Visual Studio 2010启动并运行。在Windows 8 Developer Preview中,也已从Metro的Visual Studio 11启动并运行了它。但是,Metro版本仍然缺乏纹理,因此我的多边形现在只是被着色了。问题是Metro DLL中缺少用于加载图像的方法。 Windows Store App中的Texture2D类(从Resource类继承)都缺少这些方法:
SharpDX.Direct3D11.Resource.FromStream
SharpDX.Direct3D11.Resource.FromFile
SharpDX.Direct3D11.Resource.FromMemory
有谁知道它们是否最终将在Metro中实现?还是我可以使用另一种方法?请记住,在此之前我从未听说过DirectX或SharpDX的知识,因此我对这一切仍然很不了解。
为SharpDX查找任何类型的帮助或信息并不容易,这很可惜,因为对于使用C#的Metro 3D来说,这似乎是一个很好的解决方案。
最佳答案
我不确定我是否清楚地理解了您的问题,但是在SharpDX示例中,我发现了具有两个方法的类'TextureLoader':'LoadBitmap'和'CreateTexture2DFromBitmap'。
看,您可以使用此功能从.bmp,.png和.jpg文件加载BitmapSource:
public static BitmapSource LoadBitmap(ImagingFactory2 factory, string filename)
{
var bitmapDecoder = new SharpDX.WIC.BitmapDecoder(
factory,
filename,
SharpDX.WIC.DecodeOptions.CacheOnDemand
);
var result = new SharpDX.WIC.FormatConverter(factory);
result.Initialize(
bitmapDecoder.GetFrame(0),
SharpDX.WIC.PixelFormat.Format32bppPRGBA,
SharpDX.WIC.BitmapDitherType.None,
null,
0.0,
SharpDX.WIC.BitmapPaletteType.Custom);
return result;
}
要从BitmapSource获取Texture2D,可以使用以下命令:
public static Texture2D CreateTexture2DFromBitmap(Device device, BitmapSource bitmapSource)
{
// Allocate DataStream to receive the WIC image pixels
int stride = bitmapSource.Size.Width * 4;
using (var buffer = new SharpDX.DataStream(bitmapSource.Size.Height * stride, true, true))
{
// Copy the content of the WIC to the buffer
bitmapSource.CopyPixels(stride, buffer);
return new SharpDX.Direct3D11.Texture2D(device, new SharpDX.Direct3D11.Texture2DDescription()
{
Width = bitmapSource.Size.Width,
Height = bitmapSource.Size.Height,
ArraySize = 1,
BindFlags = SharpDX.Direct3D11.BindFlags.ShaderResource,
Usage = SharpDX.Direct3D11.ResourceUsage.Immutable,
CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None,
Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
MipLevels = 1,
OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None,
SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
}, new SharpDX.DataRectangle(buffer.DataPointer, stride));
}
}
为了使其更容易,我创建了以下函数:
public static Texture2D LoadFromFile(Device device, ImagingFactory2 factory, string fileName)
{
var bs = LoadBitmap(factory, fileName);
var texture = CreateTexture2DFromBitmap(device, bs);
return texture;
}