fastgraph.py

Created by gianfranco-oddenino

Created on July 13, 2018

1.01 KB

Script library for fast drawing of lines, rectangles, arcs, circles.
line(x1,y1,x2,y2,c): draws a line of color c from (x1,y1) to (x2,y2); x1, y1, x2, y2 can be floating-point numbers;
rect(x1,y1,x2,y2,c): draws a rectangle of color c from (x1,y1) to (x2,y2); x1, y1, x2, y2 must be integer numbers;
arc(x0,y0,x,y,a,c): draws an arc of color c with center (x0,y0) and amplitude a (in radians) starting from point (x,y); if a>0 the arc is drawn in clockwise direction, if a<0 the arc is drawn in anti-clockwise direction; x0, y0, x, y, a can be floating-point numbers;
circle(x0,y0,r,c): draws a circle of color c with center (x0,y0) and radius r; x0, y0, r can be floating-point numbers.


from math import *
from kandinsky import *

def line(x1,y1,x2,y2,c):
  dx=x2-x1; dy=y2-y1
  l=max(abs(dx),abs(dy))
  dx/=l; dy/=l
  x=x1+0.5; y=y1+0.5
  for i in range(l+1):
    set_pixel(int(x),int(y),c)
    x+=dx; y+=dy

def rect(x1,y1,x2,y2,c):
  dx=int(copysign(1,x2-x1))
  for x in range(x1,x2+dx,dx):
    set_pixel(x,y1,c)
    set_pixel(x,y2,c)
  dy=int(copysign(1,y2-y1))
  for y in range(y1+dy,y2,dy):
    set_pixel(x1,y,c)
    set_pixel(x2,y,c)

def arc(x0,y0,x,y,a,c):
  l=int(abs(a)*sqrt((x-x0)**2+(y-y0)**2)+1.5)
  da=a/l
  for i in range(l):
    set_pixel(round(x),round(y),c)
    x+=(y0-y)*da; y+=(x-x0)*da

def circle(x0,y0,r,c):
  x=r; y=0
  while x+1>y:
    set_pixel(round(x0+x),round(y0+y),c)
    set_pixel(round(x0+x),round(y0-y),c)
    set_pixel(round(x0-x),round(y0+y),c)
    set_pixel(round(x0-x),round(y0-y),c)
    set_pixel(round(x0+y),round(y0+x),c)
    set_pixel(round(x0-y),round(y0+x),c)
    set_pixel(round(x0+y),round(y0-x),c)
    set_pixel(round(x0-y),round(y0-x),c)
    x-=y/x; y+=1