c# - 将互操作颜色转换为 System.Drawing.Color

标签 c# office-interop

我正在寻找如何在 C# 中将 Microsoft.Office.Interop.Word/Excel/PowerPoint.Color 转换为 System.Drawing.Color。

我在这个论坛中发现了相反的情况herehere但我不知道如何从 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/

相关文章:

c# - 我如何知道单词列表是项目符号列表还是数字列表?

c# - 哪些 C# 编译器错误未记录?

c# - 使窗口成为 Interop.Excel Com 对象的子对象

c# - 如何检查一个类的所有公共(public)方法都是虚拟的

c# - 读取多个 XML 属性

c# - 在 Excel 工作表/单元格中嵌入文件

c# - 通过 C# 添加图片到 powerpoint 幻灯片会抛出远程过程调用失败。 (HRESULT : 0x800706BE) 的异常

.NET/COM Interop 问题 - 打开 Outlook 2003 发送邮件对话框

C#/C++ - 如何获取路径太长或权限被拒绝的目录的大小?

c# - 在LPC1768中更改keil USBHID示例以进行批量传输