我正在寻找如何在 C# 中将 Microsoft.Office.Interop.Word/Excel/PowerPoint.Color 转换为 System.Drawing.Color。
我在这个论坛中发现了相反的情况here或here但我不知道如何从 Interop Color 转换为 System.Drawing.Color。
考虑到以下因素,我了解 Interop 颜色以 RGB 表示:
RGBvalue = Red + 256*Green + 256*256*Blue
但是从 RGB 值中找到红绿蓝的值并不容易(例如,如果值为 5652,我不知道如何找到红色为 20,绿色为 22)。
您知道将 Microsoft.Office.Interop.Word/Excel/PowerPoint.Color 转换为 System.Drawing.Color(或 OLE,然后我知道如何转换)的函数吗?
最佳答案
如果您查看十六进制格式的数据,这一切都会简单得多。 5652变成了0x1614,这显然是字节0x16和0x14。或者,0x16 * 0x100 + 0x14
。
与 0x100 相乘的相反操作应该只是将其除以 0x100,但为了真正消除多余的部分,我建议使用 AND 位运算。
AND 将仅保留两个值中共有的位,因此,在二进制表示中,要仅保留最低 8 位,您需要将其与启用所有 8 位的值(即 0xFF)进行 AND 运算。 0x1614(您的“5652”示例)和 0xFF 之间的 AND(以二进制格式查看)将如下所示:
00010110 00010100 00000000 11111111 v------AND------v 00000000 00010100
As you see, it effectively cuts off everything higher than the lowest byte, resulting in 00010100b, or 0x14, or 20.
For dividing by multiples of 2, there is another bit operation that is very handy and really efficient: bit shifting. 0x100 is actually '1', shifted up by 8 bits. So to get the original value back, it just needs to be shifted down by 8 bits.
if your colour is B * 0x10000 + G * 0x100 + R
, then to reverse it:
public static Color GetColorFromInterop(Int32 val)
{
// Limit to a value containing only the bits in 0xFF
Int32 r = val & 0xFF;
// Shift down by 8 bits (meaning, divide by 0x100), then limit to 0xFF
Int32 g = (val >> 8) & 0xFF;
// Shift down by 16 bits (meaning, divide by 0x10000), then limit to 0xFF
Int32 b = (val >> 16) & 0xFF;
return Color.FromArgb(r, g, b);
}
关于c# - 将互操作颜色转换为 System.Drawing.Color,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49599650/