Files
AIO_3D_Print_Local_Screen/utils/get_bootstrap_icon.py
2026-05-16 00:44:37 +08:00

55 lines
2.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import re
import os
import base64
from PyQt6.QtGui import QPixmap, QIcon
BOOTSTRAP_ICON_BASE_PATH = "third_party/Bootstrap/bootstrap-icons-1.13.1/"
def get_colored_icon(name: str, color: str, width: int = 50, height: int = 50) -> QIcon:
"""读取SVG内容并替换currentColor为目标颜色然后生成QIcon"""
try:
path = os.path.join(BOOTSTRAP_ICON_BASE_PATH, name)
with open(path, 'r', encoding='utf-8') as f:
svg_content = f.read()
svg_content = svg_content.replace('currentColor', color)
svg_content = re.sub(r'width="\d+"', f'width="{width}"', svg_content)
svg_content = re.sub(r'height="\d+"', f'height="{height}"', svg_content)
pi = QPixmap()
pi.loadFromData(svg_content.encode('utf-8'), "SVG")
return QIcon(pi)
except Exception:
return None
def get_colored_pixmap(name: str, color: str, width: int = 16, height: int = 16, view_box: str = None) -> QPixmap:
"""读取SVG内容并替换currentColor为目标颜色然后生成QPixmap"""
try:
path = os.path.join(BOOTSTRAP_ICON_BASE_PATH, name)
with open(path, 'r', encoding='utf-8') as f:
svg_content = f.read()
svg_content = svg_content.replace('currentColor', color)
svg_content = re.sub(r'width="\d+"', f'width="{width}"', svg_content)
svg_content = re.sub(r'height="\d+"', f'height="{height}"', svg_content)
if view_box is not None:
svg_content = re.sub(r'viewBox="[^"]*"', f'viewBox="{view_box}"', svg_content)
pi = QPixmap()
pi.loadFromData(svg_content.encode('utf-8'), "SVG")
return pi
except Exception:
return None
def get_colored_svg_uri(name: str, color: str, width: int = 16, height: int = 16, view_box: str = None) -> str:
"""读取SVG内容并替换currentColor为空目标颜色最后转换为HTML可识别的Base64字符串"""
try:
path = os.path.join(BOOTSTRAP_ICON_BASE_PATH, name)
with open(path, 'r', encoding='utf-8') as f:
svg_content = f.read()
svg_content = svg_content.replace('currentColor', color)
svg_content = re.sub(r'width="\d+"', f'width="{width}"', svg_content)
svg_content = re.sub(r'height="\d+"', f'height="{height}"', svg_content)
if view_box is not None:
svg_content = re.sub(r'viewBox="[^"]*"', f'viewBox="{view_box}"', svg_content)
b64 = base64.b64encode(svg_content.encode('utf-8')).decode('utf-8')
return f"data:image/svg+xml;base64,{b64}"
except Exception:
return None