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;
}
相关推荐
降临-max几秒前
JavaWeb企业级开发---MySQL
java·开发语言·数据库·笔记·后端·mysql
一路往蓝-Anbo3 分钟前
C语言从句柄到对象 (八) —— 当对象会说话:观察者模式与事件链表
c语言·开发语言·数据结构·stm32·单片机·观察者模式·链表
郭涤生3 分钟前
fmtlib/fmt仓库熟悉
c++
GIOTTO情6 分钟前
舆情监测核心模块实战:从基础采集到智能优化
开发语言·python
思成Codes11 分钟前
Golang并发编程——CSP模型
开发语言·后端·golang
csbysj202013 分钟前
Razor C# 循环
开发语言
蕨蕨学AI19 分钟前
【Wolfram语言】35 自然语言理解
开发语言·wolfram
Knight_AL20 分钟前
深入理解Java中的函数式接口
java·开发语言·python
Chen不旧21 分钟前
Java实现三个线程顺序打印
java·开发语言
charlie11451419122 分钟前
FreeRTOS: 信号量(Semaphores)、互斥量(Mutex)与优先级继承
开发语言·笔记·学习·c·freertos·实时操作系统