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 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
|
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
const bool FILL = true ; // fill figures or not?
const int SIZE = 60 ; // change to 256 when you want
const char MARKER = '*' ;
unsigned char image[SIZE][SIZE];
// Forward declarations
int iround( double x );
void column( int j, int i1, int i2, bool solid );
void drawEllipse( int cy, int cx, int height, int width );
void drawRectangle( int top, int left, int height, int width );
void plot();
void clear();
int main()
{
int answer, top, left, height, width, cy, cx;
while( true )
{
clear();
cout << "To draw a rectangle, enter: 1 top left height width\n";
cout << "To draw an ellipse, enter: 2 cy cx height width\n";
cout << "Anything else will quit.\n";
cin >> answer;
switch( answer )
{
case 1:
{
cin >> top >> left >> height >> width;
drawRectangle( top, left, height, width );
plot();
break;
}
case 2:
{
cin >> cy >> cx >> height >> width;
drawEllipse( cy, cx, height, width );
plot();
break;
}
default:
{
return 0;
}
}
}
}
//==================
int iround( double x )
{
int i = ( x >= 0 ? x + 0.5 : x - 0.5 );
return i;
}
//==================
void column( int j, int i1, int i2, bool solid )
{
if ( j < 0 || j >= SIZE ) return; // clip left and right
if ( i1 >= 0 && i1 < SIZE ) image[i1][j] = MARKER; // clip top
if ( i2 >= 0 && i2 < SIZE ) image[i2][j] = MARKER; // clip bottom
if ( solid )
{
for ( int i = max( i1 + 1, 0 ); i <= min( i2 - 1, SIZE - 1 ); i++ ) image[i][j] = MARKER;
}
}
//==================
void drawEllipse( int cy, int cx, int height, int width )
{
double a = width / 2.0, b = height / 2.0; // ellipse semi-axes
for ( int x = iround( cx - a ); x <= iround( cx + a ); x++ )
{
double xrel = ( x - cx ) / a;
double yrel = sqrt( 1.0 - xrel * xrel );
int y1 = iround( cy - b * yrel );
int y2 = iround( cy + b * yrel );
column( x, y1, y2, FILL );
}
}
//==================
void drawRectangle( int top, int left, int height, int width )
{
int y1 = top, y2 = top + height;
column( left , y1, y2, true );
column( left + width, y1, y2, true );
for ( int x = left + 1; x <= left + width - 1; x++ ) column( x, y1, y2, FILL );
}
//==================
void plot()
{
for ( int i = 0; i < SIZE; i++ )
{
for (int j = 0; j < SIZE; j++ ) cout << image[i][j];
cout << '\n';
}
}
//==================
void clear()
{
for ( int i = 0; i < SIZE; i++ )
{
for (int j = 0; j < SIZE; j++ ) image[i][j] = ' ';
}
}
//==================
|