C#中实现Microsoft.Office.Interop.Color转System.Drawing.Color
把Office互操作Color转成System.Drawing.Color的方法
其实从Office互操作的RGB值拆分出红、绿、蓝分量真的没你想的那么复杂,用基础的数学运算就能轻松搞定。先给你拆解下原理:
已知Office互操作的Color对应的RGB值计算方式是 RGBvalue = Red + 256*Green + 256²*Blue,那反过来拆分各分量的逻辑就是:
- 红色分量:直接取RGB值对256取余(因为红色是没被256乘过的部分)
- 绿色分量:先把RGB值除以256,再对256取余(去掉红色部分后,剩下的就是绿色和蓝色的部分,再取余得到绿色)
- 蓝色分量:把RGB值除以256的平方(也就是65536),得到的整数就是蓝色分量
比如你提到的数值5652,计算一下:
- 红色:
5652 % 256 = 20 - 绿色:
(5652 / 256) % 256 = 22 % 256 =22 - 蓝色:
5652 / 65536 = 0
对应的System.Drawing.Color就是Color.FromArgb(20,22,0),完全没问题。
我给你写了一个C#的扩展方法,不管是Word、Excel还是PowerPoint的互操作Color,都能直接用:
using System.Drawing; // 根据你实际引用的Office组件替换下面的命名空间 using Microsoft.Office.Interop.Word; public static class OfficeColorHelper { // 扩展方法,直接给Office互操作的Color类型添加转换方法 public static Color ToSystemDrawingColor(this Color officeColor) { int rgbValue = officeColor; int red = rgbValue % 256; int green = (rgbValue / 256) % 256; int blue = rgbValue / 65536; // 如果需要带Alpha通道(不透明),可以用Color.FromArgb(255, red, green, blue) return Color.FromArgb(red, green, blue); } }
使用的时候也很简单,比如你有一个Word的Color对象:
var wordColor = someWordDocument.Content.Font.Color; var drawingColor = wordColor.ToSystemDrawingColor();
这样就能轻松完成转换啦~
内容的提问来源于stack exchange,提问作者Freddlow
相关产品推荐
相关产品推荐

