C++入門/Scalable Vector Graphics

-,東京都立大学,情報科学科
戻る

ここでは Scalable Vector Graphics (SVG)に出力する方法をかんたんに紹介する.ファイルに文字列を出力する知識があるとする.

SVG とは線分や円など基本的幾何学図形を組み合わせて絵を描く命令を,文字列で記述したテキストファイルである.記述の形式には Extensible Markup Language (XML)を用いている.XMLが読み込めるプログラムならば,SVGに特化していなくても内容を編集できるという扱いやすい形式となっている.

以下はかんたんだが,放物線を描く例である.

#include <iostream>
#include <fstream>
using namespace std;

int main(){
    ofstream of("sample.svg");

    of << "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"-2 -2 4 4\">\n"; // Output Header,viewBox= x, y 座標の開始位置,幅,高さ
    double x_p = 0;
    double y_p = 0;
    double n = 8+1;
    double dx = 1.0/(n-1);
    double r = 1.0/32;
    for(double i=0;i<n;++i){
        double x = x_p + dx;
        double y = x*x;
        // 線分を描画する.2点必要なため,x, y, x_p, y_p を用意する.
        // y 座標は上下反転
        of << "<circle cx='" << x_p << "' cy='" << -y_p << "' r='" << r << "' style=\"stroke:rgb(0,0,0);stroke-width:0.002\" />\n";
        x_p = x;
        y_p = y;
    }
    of << "</svg>\n";
}
    

出力されたファイルはテキストエディタで開くと次のようになるはずである.

<svg xmlns="http://www.w3.org/2000/svg" viewBox="-2 -2 4 4">
<circle cx='0' cy='-0' r='0.03125' style="stroke:rgb(0,0,0);stroke-width:0.002" />
<circle cx='0.125' cy='-0.015625' r='0.03125' style="stroke:rgb(0,0,0);stroke-width:0.002" />
<circle cx='0.25' cy='-0.0625' r='0.03125' style="stroke:rgb(0,0,0);stroke-width:0.002" />
<circle cx='0.375' cy='-0.140625' r='0.03125' style="stroke:rgb(0,0,0);stroke-width:0.002" />
<circle cx='0.5' cy='-0.25' r='0.03125' style="stroke:rgb(0,0,0);stroke-width:0.002" />
<circle cx='0.625' cy='-0.390625' r='0.03125' style="stroke:rgb(0,0,0);stroke-width:0.002" />
<circle cx='0.75' cy='-0.5625' r='0.03125' style="stroke:rgb(0,0,0);stroke-width:0.002" />
<circle cx='0.875' cy='-0.765625' r='0.03125' style="stroke:rgb(0,0,0);stroke-width:0.002" />
<circle cx='1' cy='-1' r='0.03125' style="stroke:rgb(0,0,0);stroke-width:0.002" />
</svg>

これはファイルに保存しておけば,Webブラウザで開くことができ,次のように表示されるはずと思う.余白がやたらと大きいが,これは,のviewBoxのあとに設定している値で調節することができる.気になる方はここをいじられたい.

We can define a text using the following syntax in the SVG file.

<text x="-0.2" y ="0.5" fill="red" font-size="0.1" >
This is a graph I created myself!
</text>

is an example SVG includes text along with parabolic curve. We also can draw a line using line element. Search on Web to learn the use of line element in SVG.

Example of text in SVG

初学者は,出力が絵で見てわかる方法を何かしら用意したほうがいい.Excelによるグラフの描画は無いよりはいいが,自由度が低すぎるため,他の方法もあったほうが良い.SVGは少し自由度が高すぎるとおもうが,できないよりはマシで,ソフトウェアの操作方法を覚える手間も無いことからかんたんなため,おすすめである.SVGは他にも楕円を描けたり,色々できる.以下は私が描いた絵である.Inkscapeを使い描かれている.