使用按位运算混合 Alpha 颜色

发布于 2024-10-13 04:15:32 字数 200 浏览 3 评论 0原文

我有下面的代码以 ARGB 格式混合 alpha 颜色:

a、b、o 是整数,但应始终落在 [0x00ffffff,0xffffffff]

o = ( ( ( a >> 24 ) * ( b >> 24 ) ) >> 8) << 24;

有什么办法可以优化它吗?

谢谢!

I have code below to blend alpha color in ARGB format:

a, b, o are integers, but should always fall in [0x00ffffff,0xffffffff]

o = ( ( ( a >> 24 ) * ( b >> 24 ) ) >> 8 ) << 24;

Is there anyway to optimize it?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

放手` 2024-10-20 04:15:32

这不会执行 alpha 混合。这只是组合了两个像素的 Alpha 分量。它也可能与您在不直接进行组装的情况下获得的效率一样高。不过,如果您可以使用指针,您可能会更快一些:

byte* pa = (byte*)&a;
byte* pb = (byte*)&b;
byte* po = (byte*)&o;

po[3] = pa[3] * pb[3] >> 8;

这可以节省大部分移位操作。请注意,这假设是小端机器。如果您在大端处理器上运行,则它会变得更好:

*po = *pa * *pb >> 8;

在任何一种情况下,您都可以通过内联执行所有指针转换将其转换为单行代码,但它有点难以阅读。

((byte*)&o)[3] = ((byte*)&a)[3] * ((byte*)&b)[3] >> 8;

或者

*((byte*)&o) = *((byte*)&a) * *((byte*)&b) >> 8;

That doesn't perform the alpha blending. That just combines the alpha component of two pixels. It's also probably about as efficient as you're going to get without going directly to assembly. If you can use pointers, you might get a little faster, though:

byte* pa = (byte*)&a;
byte* pb = (byte*)&b;
byte* po = (byte*)&o;

po[3] = pa[3] * pb[3] >> 8;

This saves most of the shifting. Note that this assumes a little-endian machine. If you're running on a big-endian processor, it becomes even better with:

*po = *pa * *pb >> 8;

In either case, you can turn this into a one-liner by doing all the pointer casting inline, but it gets a bit hard to read.

((byte*)&o)[3] = ((byte*)&a)[3] * ((byte*)&b)[3] >> 8;

or

*((byte*)&o) = *((byte*)&a) * *((byte*)&b) >> 8;
哑剧 2024-10-20 04:15:32
unsigned int blend(unsigned int a, unsigned int b)
{
  return (((a >> 24) * (b >> 24)) << 16) & 0xFF000000;
}

这就是你想做的吗?根据你的说法,我不认为这更快,但更准确。

如果您不需要使用按位运算符,您也可以使用指针,如其他解决方案所示。

unsigned int blend(unsigned int a, unsigned int b)
{
  return (((a >> 24) * (b >> 24)) << 16) & 0xFF000000;
}

Is this what you are trying to do? I don't think this is any faster though, but more accuracte according to what you stated.

If you don't need to use bitwise operators you can use pointers too, as shown by other solutions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文