问题描述
关于在运行时从图像加载纹理(除了只能在 PC 上执行此操作)有什么需要了解的?
What is there to know about (apart from only being able to do that on PC) loading textures from images at runtime?
推荐答案
我也一直专门从流加载我的纹理,我能想到的唯一危险"是预乘 Alpha.您要么需要在加载时处理每个纹理,要么在禁用预乘 alpha 的情况下进行渲染.肖恩哈格里夫斯写了一个 关于这个主题的很棒的博客文章.在评论中,他提到:
I've been exclusively loading my textures from streams as well, and the only "danger" that I can come up with is Premultiplied Alphas. You'll either need to process each texture as you load it, or render with premultiplied alphas disabled. Shawn Hargreaves wrote a great blog article on this subject. In the comments, he mentions:
如果你不通过我们的内容管道,你必须自己处理格式转换,或者干脆不使用预乘 alpha
所以用 BlendState.NonPremultiplied 应该可以工作.
So initializing your sprite batch(es) with BlendState.NonPremultiplied should work.
在我的游戏中,我在加载时处理了每个纹理.
In my game, I have processed each texture when I load it.
这是我的方法:
private static void PreMultiplyAlphas(Texture2D ret)
{
var data = new Byte4[ret.Width * ret.Height];
ret.GetData(data);
for (var i = 0; i < data.Length; i++)
{
var vec = data[i].ToVector4();
var alpha = vec.W / 255.0f;
var a = (Int32)(vec.W);
var r = (Int32)(alpha * vec.X);
var g = (Int32)(alpha * vec.Y);
var b = (Int32)(alpha * vec.Z);
data[i].PackedValue = (UInt32)((a << 24) + (b << 16) + (g << 8) + r);
}
ret.SetData(data);
}
如您所见,它所做的只是将颜色通道乘以 alpha,然后将其塞回到纹理中.如果没有这个,你的精灵可能会显得更亮/更暗?比他们应该的.(免责声明:上面的方法不是我写的,是我一个朋友写的)
As you can see, all it does is multiply the color channels by the alpha, then stuff it back into the texture. Without this, your sprites will likely appear brighter/darker? than they should. (disclaimer: I didn't write the method above, a friend of mine did)
这篇关于在 XNA 中在运行时从图像加载纹理有什么风险?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!