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;
}
相关推荐
Ws_13 小时前
WPF 面试题 + 参考答案,偏 C# 桌面端开发高频。
开发语言·c#·wpf
程序猿编码13 小时前
如何把远程文件变化“骗“成本地inotify事件:一个LD_PRELOAD钩子
c语言·开发语言·网络·tcp/ip·安全
lDevinl13 小时前
【无标题】
数据结构·c++·青少年编程
zincsweet13 小时前
System V 共享内存:原理剖析、代码架构分析与双端通信实战
linux·c++
星空椰1 天前
Python 面向对象高级:继承与类定义详解
开发语言·python
wunaiqiezixin1 天前
如何在C++中创建和管理线程
c++
白露与泡影1 天前
2026大厂Java面试题大全!牛客网最新版
java·开发语言
凯瑟琳.奥古斯特1 天前
高阶子查询题目精炼
开发语言·数据库·python·职场和发展·数据库开发
雪度娃娃1 天前
转向现代C++——在意为改写的函数添加 override
开发语言·c++
王老师青少年编程1 天前
csp信奥赛C++高频考点专项训练之前缀和&差分 --【一维差分】:[NOIP 2018 提高组] 铺设道路
c++·前缀和·差分·csp·高频考点·信奥赛·铺设道路