Reputation: 126
I return back with another dummy question as I'm newbie. I wrote a code in c to fill a 2D array using Bresenham's algorithm. The codes fill 2D array with successive circles with:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
double *v;
int i;
v = (double*)malloc(101*101*sizeof(double));
for(i=0;i<101*101;i++)
{
v[i]=0.0;
}
for(i=0;i<73;i++)
{
draw_circle(v, 101,101,51,51,i,(double)i);
}
write_arraya(v,"test.txt",101,101);
free(v);
return 1;
}
which used Bresenham's algorithm
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void draw_circle (double *v, int m, int n, int xr, int yr, int radius, double value)
{
int x, y;
int l;
l = (int) radius * cos (M_PI / 4);
for (x = 0; x <= l; x++)
{
y = (int) sqrt ((double) (radius * radius) - (x * x));
set_value (v, m, n, xr+x-1, yr+y-1, (double)value);
set_value (v, m, n, xr+x-1, yr-y-1, (double)value);
set_value (v, m, n, xr-x-1, yr+y-1, (double)value);
set_value (v, m, n, xr-x-1, yr-y-1, (double)value);
set_value (v, m, n, xr+y-1, yr+x-1, (double)value);
set_value (v, m, n, xr+y-1, yr-x-1, (double)value);
set_value (v, m, n, xr-y-1, yr+x-1, (double)value);
set_value (v, m, n, xr-y-1, yr-x-1, (double)value);
printf("x= %d, y=%d\n", x, y);
}
}
and setting values by:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void set_value (double *v, int m, int n, int i, int j, double value)
{
if(i>=0 && i<m && j>=0 && j<n)
{
v[i*n+j]=(double)value;
}
}
and write them to a text file with
#include <stdio.h>
#include <stdlib.h>
void write_arraya(double *v, char file_name[], int row, int col)
{
FILE *fp;
int i, j;
fp = fopen(file_name, "w");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
fprintf(fp,"%e ",v[i*col+j]);
}
fprintf(fp,"\n");
}
fclose(fp);
}
these are works properly but the main question is about unfilled elements in array. There are some elements remains with zero values. I would like to fill these values with a proper value. Note that the speed of code is important for me so any other suggestion is wellcome. Is there any idea? I attached the fig I observed from text file
The dark blue pixels (mostly black) are unfilled element in array
Upvotes: 3
Views: 740
Reputation: 20333
An inelegant way would be to draw 2 (or if needed 3) different circles for every possible radius, but a slightly different center point (one for x,y an other for x+1, y). - In this case your array must be big enough to handle the shifted circles (have an additional column).
A much nicer solution would be not to draw circles at all. Just iterate through the pixels, get their distance from center (using the Pythagorean theorem, which is already utilized in your code), then calculate the color based on the distance. - You can optimize this to do only one quarter of the area. And further optimize to do only one eighth.
Upvotes: 1