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;
}
相关推荐
女王大人万岁1 分钟前
Go语言JSON标准库(encoding/json):功能解析与实战指南
服务器·开发语言·后端·golang·json
wjs20243 分钟前
Scala 基础语法
开发语言
.ZGR.4 分钟前
从游戏到实战的线程进阶之旅:智能无人机防空平台
java·开发语言·无人机
上海合宙LuatOS5 分钟前
LuatOS ——fota 升级教程
开发语言·人工智能·单片机·嵌入式硬件·物联网·php·硬件工程
NWU_白杨6 分钟前
智能无人机平台V4
java·开发语言·无人机
小高Baby@6 分钟前
Go语言中面向对象的三大特性之继承的理解
开发语言·后端·golang
小高Baby@6 分钟前
Go语言中面向对象的三大特性之封装的理解
开发语言·后端·golang
是店小二呀11 分钟前
Visual Studio C++ 工程架构深度解析:从 .vcxproj 到 Qt MOC 的文件管理实录
c++·qt·visual studio
木卫二号Coding12 分钟前
第七十七篇-V100+llama-cpp-python-server+Qwen3-30B+GGUF
开发语言·python·llama
半夏知半秋12 分钟前
lua5.5版本新特性学习
开发语言·笔记·学习