LoginSignup
3
7

More than 5 years have passed since last update.

簡易版SVG作成ライブラリ(C++版)

Last updated at Posted at 2015-10-15

概要

以前,C++でSVGを書くための簡易的なライブラリを作成したのでご紹介.主に研究用途でベクタ形式の図がいる時に使っています.

ダウンロード

SvgDrawerクラス

コンストラクタ,デストラクタ

  • SvgDrawer( const int width, const int height, const std::string& filename = std::string( "draw.svg" ) ) コンストラクタ.(width, height)はSVGファイルの画像(?)サイズ. filenameは出力ファイル名
  • void setViewBox ( const double mnx, const double mny, const double mxx, const double may ) 描画可能範囲の指定.

属性の設定

  • void init ( void ) 各種パラメータの初期化.破線を実線にして,線幅を1,線の色,塗りつぶし色を黒にする.
  • void setStrokeWidth ( const double width ) 線幅を設定する.
  • void setStrokeColor( const std::string &col ) 線の色を設定する.色は,文字列で与える."#AAC032"のような16進法,"yellow"のような直接指定する方法,SVGで使われている方法であればok.
  • void setFillColor( const std::string &col ) 塗りつぶし色を指定.
  • void setStrokeDash( const int dash_pitch ) 破線の間隔を指定.

描画

幾何要素を実際に描きます.色などの属性は,クラス内で設定されたものを使います.

  • void drawLine ( const double x0 , const double y0, const double x1, const double y1 ) (x0, y0) - (x1,y1)に線を引く.座標系はsetViewBoxで指定したものが使われる.
  • void drawCircle ( const double cx, const double cy, const double r ) (cx, cy)を中心とした半径rの円を描く
  • void drawRect ( const double x0, const double y0, const double w, const double h ) (x0, y0)を原点として,サイズ(w,h)の視覚を描く

例題

  • コンパイル時に標準ライブラリ以外は必要ありません
example.cpp
#include "SvgDrawer.hpp"

int main ( int argc, char** argv ) {
    mi::SvgDrawer drawer ( 300, 300, "test.svg");/// サイズは300x300 
    drawer.setViewBox( -2, -2, 2, 2); //(-2,-2)-(2,2)の範囲

    drawer.setStrokeColor("red");
    drawer.drawLine(-1.5, -1.5, -1.5, 1.5);
    drawer.setStrokeColor("blue");
    drawer.drawLine(-1.5, 1.5, 1.5, 1.5);
    drawer.setStrokeColor("yellow");
    drawer.drawLine(1.5, 1.5, 1.5, -1.5);
    drawer.setStrokeColor("green");
    drawer.drawLine(1.5, -1.5, -1.5, -1.5);
    // automatically saved
    return 0;
}

結果

test.svg
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width= "300" height="300">
<line x1="37.5" y1="262.5" x2="37.5" y2="37.5" stroke-width="1" stroke="red" />
<line x1="37.5" y1="37.5" x2="262.5" y2="37.5" stroke-width="1" stroke="blue" />
<line x1="262.5" y1="37.5" x2="262.5" y2="262.5" stroke-width="1" stroke="yellow" />
<line x1="262.5" y1="262.5" x2="37.5" y2="262.5" stroke-width="1" stroke="green" />
</svg>

test.png

3
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
7