1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
|
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cmath>
using namespace std;
template <typename T> void write( ostream &out, const string &item, const vector< pair<string,T> > &V, const vector< pair<string,string> > &W = {} )
{
const char q = '\"';
out << "<" << item;
for ( auto pr : V ) out << " " << pr.first << "=" << q << pr.second << q;
for ( auto pr : W ) out << " " << pr.first << "=" << q << pr.second << q;
out << " />\n";
}
class Svg
{
ofstream out;
string colour = "red";
string fill = "green";
double width = 4;
public:
Svg( string filename, int width = 1000, int height = 1000, string background = "#FFFFFF" )
{
out.open( filename );
out << "<?xml version=\"1.0\" standalone=\"no\"?>\n"
<< "<svg "
<< "xmlns=\"http://www.w3.org/2000/svg\" "
<< "width=\"" << width << "\" height=\"" << height << "\" "
<< "style=\"background: " << background << "\" "
<< ">\n";
}
~Svg()
{
out << "</svg>";
out.close();
}
void setcolour( const string &s ){ colour = s; }
void setfill ( const string &s ){ fill = s; }
void setwidth ( double w ){ width = w; }
void line( double x1, double y1, double x2, double y2 )
{
write<double>( out, "line", { { "x1", x1 }, { "y1", y1 }, { "x2", x2 }, { "y2", y2 }, { "stroke-width", width } },
{ { "stroke", colour }, { "fill", fill } } );
}
void rectangle( double x, double y, double w, double h )
{
write<double>( out, "rect", { { "x", x }, { "y", y }, { "width", w }, { "height", h }, { "stroke-width", width } },
{ { "stroke", colour }, { "fill", fill } } );
}
void circle( double r, double cx, double cy )
{
write<double>( out, "circle", { { "r", r }, { "cx", cx }, { "cy", cy }, { "stroke-width", width } },
{ { "stroke", colour }, { "fill", fill } } );
}
};
int main()
{
double PI = 3.14159;
string filename = "plot.svg";
double width = 800, height = 800;
double r0 = 10, dr = 5;
double theta0 = 0, dtheta = 20;
int npoints = 70;
Svg svg( filename, width, height );
svg.setcolour( "red" );
svg.setfill( "blue" );
svg.setwidth( 2 );
for ( int i = 0; i < npoints; i++ )
{
double r = r0 + i * dr;
double theta = theta0 + i * dtheta;
double x = 0.5 * width + r * cos( theta * PI /180.0 );
double y = 0.5 * height - r * sin( theta * PI /180.0 );
double radius = 0.03 * r;
svg.circle( radius, x, y );
}
svg.setcolour( "black" );
svg.setfill( "orange" );
svg.setwidth( 4 );
svg.rectangle( 0.0, 0.0, 0.2 * width, 0.2 * height );
svg.setcolour( "violet" );
svg.line( 0.2 * width, 0.2 * height, 1.0 * width, 1.0 * height );
}
|