Improve the Handling of Color Information Format During PDF Generation
Showing
1 changed file
with
33 additions
and
2 deletions
| @@ -199,7 +199,7 @@ class ChartToSVGConverter: | @@ -199,7 +199,7 @@ class ChartToSVGConverter: | ||
| 199 | 199 | ||
| 200 | return fig, ax | 200 | return fig, ax |
| 201 | 201 | ||
| 202 | - def _parse_color(self, color: Any) -> str: | 202 | + def _parse_color(self, color: Any) -> Any: |
| 203 | """ | 203 | """ |
| 204 | 解析颜色值,将CSS格式转换为matplotlib支持的格式 | 204 | 解析颜色值,将CSS格式转换为matplotlib支持的格式 |
| 205 | 205 | ||
| @@ -207,8 +207,39 @@ class ChartToSVGConverter: | @@ -207,8 +207,39 @@ class ChartToSVGConverter: | ||
| 207 | color: 颜色值(可能是CSS格式如rgba()或十六进制或CSS变量) | 207 | color: 颜色值(可能是CSS格式如rgba()或十六进制或CSS变量) |
| 208 | 208 | ||
| 209 | 返回: | 209 | 返回: |
| 210 | - str: matplotlib支持的颜色格式 | 210 | + matplotlib支持的颜色格式(hex字符串或RGB(A)元组) |
| 211 | """ | 211 | """ |
| 212 | + if color is None: | ||
| 213 | + return None | ||
| 214 | + | ||
| 215 | + # 处理numpy数组,统一转为原生列表 | ||
| 216 | + _np = globals().get("np") | ||
| 217 | + if _np is not None and hasattr(_np, "ndarray") and isinstance(color, _np.ndarray): | ||
| 218 | + color = color.tolist() | ||
| 219 | + | ||
| 220 | + # 直接透传已经是序列的颜色(如 (r,g,b,a)),避免被转成字符串后失效 | ||
| 221 | + if isinstance(color, (list, tuple)): | ||
| 222 | + if len(color) in (3, 4) and all(isinstance(c, (int, float)) for c in color): | ||
| 223 | + normalized = [] | ||
| 224 | + for idx, channel in enumerate(color): | ||
| 225 | + # Matplotlib接受0-1之间的浮点数,若值>1则按0-255来源归一化 | ||
| 226 | + value = float(channel) | ||
| 227 | + if value > 1: | ||
| 228 | + value = value / 255.0 | ||
| 229 | + # 只对RGB通道做强制裁剪,alpha按0-1裁剪 | ||
| 230 | + if idx < 3: | ||
| 231 | + value = max(0.0, min(value, 1.0)) | ||
| 232 | + else: | ||
| 233 | + value = max(0.0, min(value, 1.0)) | ||
| 234 | + normalized.append(value) | ||
| 235 | + return tuple(normalized) | ||
| 236 | + | ||
| 237 | + try: | ||
| 238 | + return tuple(color) | ||
| 239 | + except Exception: | ||
| 240 | + return color | ||
| 241 | + | ||
| 242 | + # 其余非字符串类型保持原有字符串回退策略 | ||
| 212 | if not isinstance(color, str): | 243 | if not isinstance(color, str): |
| 213 | return str(color) | 244 | return str(color) |
| 214 | 245 |
-
Please register or login to post a comment