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;
}
相关推荐
蜡笔小马2 分钟前
13.C++设计模式-策略模式
c++·设计模式·策略模式
我命由我123455 分钟前
Android 开发问题:TextView 内容超过宽度时,默认不会换行
android·开发语言·java-ee·android studio·android jetpack·android-studio·android runtime
计算机安禾5 分钟前
【c++面向对象编程】第36篇:析构函数应永远不抛出异常——原因与最佳实践
开发语言·c++
一条泥憨鱼9 分钟前
【Java 进阶】LinkedHashMap 与 TreeMap
java·开发语言·数据结构·笔记·后端·学习
ゆづき9 分钟前
假如编程语言们有外号
java·c语言·c++·python·学习·c#·生活
凤山老林11 分钟前
63-Java LinkedList(链表)
java·开发语言·链表
恣艺17 分钟前
用Go从零实现一个高性能KV存储引擎:B+Tree索引、WAL持久化、LRU缓存的工程实践
开发语言·数据库·redis·缓存·golang
kkeeper~9 小时前
0基础C语言积跬步之深入理解指针(5下)
c语言·开发语言
一直不明飞行9 小时前
Java的equals(),hashCode()应该在什么时候重写
java·开发语言·jvm
REDcker9 小时前
有限状态机与状态模式详解 FSM建模Java状态模式与C++表驱动模板实践
java·c++·状态模式