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;
}
相关推荐
不正经学生4 小时前
C语言预处理详解:编译器真正动手之前的那些事
c语言·开发语言·算法·面试·bug
门思科技5 小时前
LoRaWAN 设备类别:Class A、B、C 对比与选型指南
c语言·开发语言·php
恋恋西风7 小时前
C++ 理解 std::thread 在单核和多核上的行为差异
开发语言·c++
Brilliantwxx7 小时前
【Linux】 进程(9)程序与进程地址空间(基础+进阶+面试题)
linux·运维·服务器·开发语言·c++
BizzZ_8 小时前
C++(22)——类型转换和IO流
开发语言·c++
小范同学_8 小时前
JDK1.7 与 JDK1.8 HashMap 底层原理对比 + 数组并发扩容死循环详解
java·开发语言
geovindu8 小时前
CSharp: 万年历
开发语言·后端·c#·.net
我找到地球的支点啦9 小时前
Matlab系列(009) 一CRC循环冗余校验详解
开发语言·数据结构·算法·matlab·信息与通信
予昊9 小时前
从零实现“在线五子棋对战“:WebSocket 实时通信 + 段位匹配
java·开发语言·网络·websocket
weixin_461408589 小时前
Mybatis-flex小记
java·开发语言·mybatis