我有用于计算像素不透明度的C#代码,它在XNA中使用,我如何才能提高它的性能?
public static uint GetPixelForOpacity(uint pixelBackground, uint pixelForeground, uint pixelCanvasAlpha)
{
byte surfaceR = (byte)((pixelForeground & 0x00FF0000) >> 16);
byte surfaceG = (byte)((pixelForeground & 0x0000FF00) >> 8);
byte surfaceB = (byte)((pixelForeground & 0x000000FF));
byte sourceR = (byte)((pixelBackground & 0x00FF0000) >> 16);
byte sourceG = (byte)((pixelBackground & 0x0000FF00) >> 8);
byte sourceB = (byte)((pixelBackground & 0x000000FF));
uint newR = sourceR * pixelCanvasAlpha / 256 + surfaceR * (255 - pixelCanvasAlpha) / 256;
uint newG = sourceG * pixelCanvasAlpha / 256 + surfaceG * (255 - pixelCanvasAlpha) / 256;
uint newB = sourceB * pixelCanvasAlpha / 256 + surfaceB * (255 - pixelCanvasAlpha) / 256;
return (uint)255 << 24 | newR << 16 | newG << 8 | newB;
}
答案 0 :(得分:3)
答案 1 :(得分:1)
将pixelCanvasAlpha / 256
替换为pixelCanvasAlpha >> 8
。不要用整数类型除以2的幂,移位总是更快。此外,unchecked
应该有所帮助。
答案 2 :(得分:0)
我对此表示怀疑,但bitwise not
可能比255-n更快
uint newR = (sourceR * pixelCanvasAlpha + surfaceR * (uint)(byte)~pixelCanvasAlpha) >> 8;
或
uint newR = (sourceR * pixelCanvasAlpha + surfaceR * ~pixelCanvasAlpha & 0x000000FF) >> 8;
要知道的唯一方法是进行基准测试。