C++:使用tinyXML生成矢量图svg

先说一下tinyXML库的配置:

很简单,去下面官网下载

TinyXML download | SourceForge.net

解压后是这样

直接将红框中的几个文件放到项目中即可使用

关于svg文件,SVG是基于XML的可扩展矢量图形,svg是xml文件,但是xml范围更广不一定是svg

使用tinyxml库就是按照svg的格式,将内容写为xml文件,其实也可以写为svg格式,直接打开就是图像。

将xml后缀改为svg打开看看图片

例子:

cpp 复制代码
#include "tinyxml.h"
#include<iostream>
#include<string>

int main() {
    // 创建 XML 文档对象
    TiXmlDocument doc;

    // 添加根元素
    TiXmlElement* root = new TiXmlElement("svg");
    root->SetAttribute("version", "1.1");
    root->SetAttribute("xmlns", "http://www.w3.org/2000/svg");
    root->SetAttribute("width", "400");
    root->SetAttribute("height", "300");
    doc.LinkEndChild(root);

    // 绘制棋盘格
    int cellWidth = 100;
    int cellHeight = 100;

    for (int row = 0; row < 3; ++row) {
        for (int col = 0; col < 4; ++col) {
            TiXmlElement* rect = new TiXmlElement("rect");
            rect->SetAttribute("x", std::to_string(col * cellWidth).c_str());
            rect->SetAttribute("y", std::to_string(row * cellHeight).c_str());
            rect->SetAttribute("width", std::to_string(cellWidth).c_str());
            rect->SetAttribute("height", std::to_string(cellHeight).c_str());

            if ((row + col) % 2 == 0) {
                rect->SetAttribute("fill", "white");
            }
            else {
                rect->SetAttribute("fill", "black");
            }

            root->LinkEndChild(rect);
        }
    }

    // 保存为 SVG 文件或xml文件
    doc.SaveFile("chessboard.xml");

    return 0;
}
相关推荐
_upupup14 分钟前
异常(C++)
java·开发语言·jvm
ebiobiz17 分钟前
基于 GD32 Embedded Builder (GEB) 与 Nimmake 的 MCU 工程搭建指南
c++·python·单片机·嵌入式硬件·mcu
hetao173383719 分钟前
2026-09-29 hetao1733837 的刷题记录
c++·算法
:mnong26 分钟前
几何内核“四大金刚“:ACIS、Parasolid、CGM、Open CASCADE 核心特征深度解析
c++·cad·cax
霸道流氓气质28 分钟前
ComfyUI 图像生成工作流完全指南:从节点编排到Java生产级图像生产实战
java·开发语言·人工智能
by209991 小时前
从 malloc/free 到 new/delete:真正理解 C++ 中的内存管理与对象生命周期
c语言·c++·经验分享·动态内存管理
ShyanZh1 小时前
【Python3基础】13-Python 常用设计模式
开发语言·python·设计模式
m0_380743871 小时前
Qt侧边栏布局的实现示例
开发语言·c++
zh_xuan1 小时前
c++ 23 std::out_ptr用法
开发语言·c++23·out_ptr
陆卿之2 小时前
Java对接DeepSeek
java·开发语言·人工智能