void SetSVGBackColor(QDomElement& elem, QString strtagname, QString strattr, QString strattrval)
{
if (elem.tagName().compare(strtagname) == 0)
{
QString before_color = elem.attribute(strattr);
elem.setAttribute(strattr, strattrval);
QString color = elem.attribute(strattr);
}
for (int i = 0; i < elem.childNodes().count(); i++)
{
if (!elem.childNodes().at(i).isElement())
{
continue;
}
SetSVGBackColor(elem.childNodes().at(i).toElement(), strtagname, strattr, strattrval);
}
}
void init_svg(QString img_path, QImage* image, QString color)
{
QFile file(img_path);
if (file.open(QIODevice::ReadOnly))
{
QByteArray svg_buffer = file.readAll();
file.close();
QDomDocument doc;
doc.setContent(svg_buffer);
SetSVGBackColor(doc.documentElement(), "path", "fill", color);
QSvgRenderer* render_image = new QSvgRenderer(doc.toByteArray());
QPainter painter_image(image);
painter_image.setCompositionMode(QPainter::CompositionMode_Clear); // 清除画布
painter_image.fillRect(image->rect(), Qt::transparent); // 填充透明色
painter_image.setCompositionMode(QPainter::CompositionMode_SourceOver); // 恢复默认值
render_image->render(&painter_image);
delete render_image;
}
}
参数:
指定svg图片的文件(svg_path)
指定希望生成的png的颜色(color)
指定希望得到的png文件的位置(file_path)
void distribution_system::init_a_png(QString svg_name,QString png_name,QString color)
{
QString path = QApplication::applicationDirPath() + "/images/navbar/";
QString svg_path = path + svg_name + ".svg";
QString file_path = path + png_name + ".png";
QImage* image = new QImage(200, 200, QImage::Format_ARGB32);
init_svg(svg_path, image, color);
image->save(file_path, "png", -1);
delete image;
}