def test_text(): canvas = pyagg.Canvas("210mm", "297mm", background=(222, 222, 222), ppi=96) canvas.percent_space() canvas.draw_line([10, 10, 50, 90, 90, 10], smooth=True, fillcolor=(222, 0, 0), fillsize="2cm") canvas.draw_text((50, 20), "Once upon a time", textsize=32) canvas.draw_text((50, 30), "Someplace Near Boulder", textsize=12) canvas.draw_text((50, 40), "There was a reflection", textsize=12, textanchor="e") canvas.draw_text((50, 40), "There was a reflection", textsize=12, textanchor="w") for d in ("nw", "n", "ne", "e", "se", "s", "sw", "w"): canvas.draw_text((50, 50), d, textsize=32, textanchor=d) canvas.default_unit = "cm" canvas.draw_circle((50, 50), fillsize="1", fillcolor=(0, 222, 0)) canvas.draw_box((50, 50), fillsize="1", fillcolor=(0, 0, 0, 111)) canvas.draw_triangle((50, 50), fillsize="1", fillcolor=(0, 0, 0, 111)) canvas.default_unit = "in" canvas.draw_circle((50, 50), fillsize="1", fillcolor=(0, 222, 0, 111)) canvas.draw_box((50, 50), fillsize="1", fillcolor=(0, 0, 0, 111)) canvas.draw_triangle((50, 50), fillsize="1", fillcolor=(0, 0, 0, 111)) canvas.save("C:/Users/kimo/Desktop/ble.png") #view()
def linepattern(w,h): c = pa.Canvas(w,h,mode="RGB",background="black") incr = w*2//5 for x in range(0,w*2,incr): x += incr//2 c.draw_line([(0,x),(x,0)], fillsize=10, fillcolor="white") return c
def test_normalline(): canvas = pyagg.Canvas(1000, 500) canvas.percent_space() canvas.draw_line(linepath, fillcolor=(222, 0, 0), fillsize=0.1, outlinewidth=0.3) return canvas
def test_flowline(): canvas = pyagg.Canvas(1000, 500) canvas.percent_space() canvas.draw_line(linepath, volume=lambda p, x, y: 1 * p + 0.1, fillcolor=(222, 0, 0), outlinecolor="black", outlinewidth=0.3) return canvas
def render(self, width, height, coordspace_bbox): drawer = pyagg.Canvas(width, height, background=None) drawer.custom_space(*coordspace_bbox) # get features based on spatial index, for better speeds when zooming if not hasattr(self.data, "spindex"): self.data.create_spatial_index() spindex_features = self.data.quick_overlap(coordspace_bbox) # draw each as geojson for feat in spindex_features: drawer.draw_geojson(feat.geometry, **self.styleoptions) self.img = drawer.get_image()
def test_arrow(): canvas = pyagg.Canvas(1000, 500) canvas.percent_space() canvas.draw_line( linepath, volume=lambda p, x, y: 1 * p + 0.1, #smooth=True, end="arrow", #lambda line,left,right: [left,right], fillcolor=(222, 0, 0), outlinecolor="black", outlinewidth=0.3) return canvas
def diagonal_left(width, height): import pyagg c = pyagg.Canvas(width, height) for frac in range(0, 100 + 1, 10): frac = frac / 100.0 x = width * frac y = height * frac c.draw_line([(x, 0), (0, y)], fillcolor='black', outlinecolor=None) c.draw_line([(x, height), (width, y)], fillcolor='black', outlinecolor=None) return c
def test_smoothline(): canvas = pyagg.Canvas(1000, 500) canvas.percent_space() for x1, x2 in zip(range(-50, 100, 10), range(0, 150, 10)): canvas.draw_line([x2, 0, x1, 100]) canvas.draw_line([10, 10, 50, 90, 90, 10], smooth=True, fillcolor=(222, 0, 0), fillsize=2) canvas.draw_text("Hello", (50, 50), textfont="segoe print bold", textsize=55) return canvas
def __init__(self, layers, width, height, background=None, *args, **kwargs): # remember and be remembered by the layergroup self.layers = layers layers.connected_maps.append(self) # create the drawer with a default unprojected lat-long coordinate system self.drawer = pyagg.Canvas(width, height, background) self.drawer.geographic_space() self.img = self.drawer.get_image()
def from_vector(vectordata, valuefield, cellwidth, cellheight, **options): # ie rasterize # calculate required raster size from cell dimensions vectorbbox = vectordata.bbox xmin, ymin, xmax, ymax = vectorbbox oldwidth, oldheight = xmax - xmin, ymax - ymin newwidth, newheight = oldwidth / float(cellwidth), oldheight / float( cellheight) newwidth, newheight = int(round(newwidth)), int(round(newheight)) # simply create pyagg image with specified image size canvas = pyagg.Canvas(newwidth, newheight) # set the coordspace to vectordata bbox canvas.custom_space(*vectorbbox) # draw the vector data for feat in vectordata: geotype = feat.geometry["type"] # NOTE: NEED TO MAKE SURE IS NUMBER, AND PYAGG ONLY TAKES RGB VALID NRS # FIX... value = feat[valuefield] # polygon, basic black fill, no outline if "Polygon" in geotype: canvas.draw_geojson(feat.geometry, fillcolor=(value, 0, 0), outlinecolor=None) # line, 1 pixel line thickness elif "LineString" in geotype: canvas.draw_geojson(feat.geometry, fillcolor=(value, 0, 0), fillsize=1) # point, 1 pixel square size elif "Point" in geotype: canvas.draw_geojson(feat.geometry, fillcolor=(value, 0, 0), fillsize=1) # create raster from the drawn image (only first band) img = canvas.get_image().split()[0] raster = pg.Raster(image=img, cellwidth=cellwidth, cellheight=cellheight, **options) return raster
def draw_solution(boards): length_multiplier = 10 height = 20 space_between = 35 canvas_height = len(boards) * (height + space_between) canvas = pyagg.Canvas("210mm", str(canvas_height) + "px", background=(222, 222, 222), ppi=96) #canvas = pyagg.Canvas("210mm", "297mm", background=(222,222,222), ppi=96) number = 0 for b in boards: # Draw the main board x = 10 y = number * space_between + space_between x1 = 10 + length_multiplier * b.orig_length y1 = space_between * number + height canvas.draw_box(bbox=[x, y, x1, y1], fillcolor=(139, 69, 19)) number = number + 1 canvas.draw_text(str(b.orig_length) + "\"", xy=(x1 + 5, (y + y1) / 2), anchor="w", textsize=16) # Draw the pieces left = x for piece in b.pieces: right = left + piece * length_multiplier color = board_colors[randint(0, len(board_colors) - 1)] canvas.draw_box(bbox=[left, y, right, y1], fillcolor=color) canvas.draw_text(str(piece) + "\"", xy=(((left + right) / 2), y - (height / 2)), justify="left", textsize=16) left = right canvas.save("test.png") canvas.view()
import pyagg # startup canvas = pyagg.Canvas("500px", "500px", background="orange") canvas.percent_space() # draw pyagg logos background ##from random import randrange ##for _ in range(500): ## xy = (randrange(0, 100), randrange(0, 100)) ## size = randrange(1, 2+xy[1]/3) ## canvas.draw_text(xy, "PyAgg", textsize=size, textcolor=(222,222,222,100) ) # draw beer ### bubbles from random import randrange for _ in range(500): xy = (randrange(30,70), randrange(5,86)) size = "%i" % randrange(1, 2+xy[1]/10) canvas.draw_circle(xy, fillsize=size+"px", fillcolor=None, outlinewidth="1%w", outlinecolor=(222,222,222,100) ) ### the middle canvas.draw_box(bbox=[27, 90, 73, 30], fillcolor=(222,222,222,100), outlinewidth="5%w", outlinecolor=(122,122,222,100) ) ### the handle canvas.draw_line([(73,70), (90,55), (73,40)],
def render(self): import PIL.Image, PIL.ImageTk # setup matrix aspect = float(self.context.Width) / float(self.context.Height) matrix = LookAt(self.eye, self.center, self.up).Perspective(self.fovy, aspect, self.near, self.far) self.context.Shader.Matrix = matrix # render self.context.ClearColorBuffer() self.context.ClearDepthBuffer() for mesh in self.meshes: self.context.DrawMesh(mesh) self._img = PIL.ImageTk.PhotoImage(self.context.Image().PIL()) self.canvas.itemconfig(self._imgid, image=self._img) # xy map mins = [m.BoundingBox().Min for m in self.meshes] mins = [(mn.X, mn.Y, mn.Z) for mn in mins] minxs, minys, minzs = zip(*mins) minxs = list(minxs) + [self.eye.X, self.center.X, self.light.X] minys = list(minys) + [self.eye.Y, self.center.Y, self.light.Y] xmin, ymin, zmin = min(minxs), min(minys), min(minzs) maxs = [m.BoundingBox().Max for m in self.meshes] maxs = [(mn.X, mn.Y, mn.Z) for mn in maxs] maxxs, maxys, maxzs = zip(*maxs) maxxs = list(maxxs) + [self.eye.X, self.center.X, self.light.X] maxys = list(maxys) + [self.eye.Y, self.center.Y, self.light.Y] xmax, ymax, zmax = max(maxxs), max(maxys), min(maxzs) self.xyimg = xyimg = pa.Canvas(300, 300) xyimg.custom_space(xmin, ymax, xmax, ymin, lock_ratio=True) xyimg.zoom_out(1.5) xmin, ymax, xmax, ymin = xyimg.coordspace_bbox xyimg.zoom_out(1.5) # objects for m in self.meshes: bbox = m.BoundingBox() bbox = [bbox.Min.X, bbox.Min.Y, bbox.Max.X, bbox.Max.Y] xyimg.draw_box(bbox=bbox, fillcolor=(0, 255, 0), outlinewidth="1px") # eye xyimg.draw_circle((self.eye.X, self.eye.Y), fillsize="5px", fillcolor=(0, 0, 0, 255)) # center xyimg.draw_circle((self.center.X, self.center.Y), fillsize="5px", fillcolor=(255, 0, 0)) # light xyimg.draw_circle((self.light.X, self.light.Y), fillsize="5px", fillcolor=(255, 255, 0)) xyimg.draw_axis('x', xmin, xmax, 0) xyimg.draw_axis('y', ymin, ymax, 0) self.xymap['image'] = self.xymap._img = xyimg.get_tkimage()
import pyagg as pa c = pa.Canvas(500,500) c.percent_space() c.draw_text("""Long paragraph broken up into lines and aligned to the left""", (0,0), anchor="nw", justify="left") c.draw_text("""Long paragraph broken up into lines aligned to the center and rotated""", (50,50), anchor="center", justify="center", rotate=13) c.draw_text("""Long paragraph broken up into lines and aligned to the right""", (100,100), anchor="se", justify="right") c.draw_text("This is an interesing textbox that should be autowrapped", bbox=[60,60,100,70]) c.draw_text("25%", (100,0), textsize="25%h", anchor="ne") ##for size in range(1,50,5): ## c.draw_text("%s%%"%size, (500,500/100*size), textsize="%s%%w"%size, anchor="e") c.view()
def test_text(): canvas = pyagg.Canvas("210mm", "297mm", background=(222, 222, 222), ppi=97) #canvas.percent_space() canvas.custom_space(0, 0, 140, 100) #canvas.flip(True, True) #canvas.rotate(30) #canvas.move("51x","51y") canvas.draw_grid(25, 25) canvas.zoom_out(1.4) canvas.draw_axis("x", 0, 140, 0, ticknum=25, ticklabeloptions={ "textsize": 30, "rotate": 40, "anchor": "sw" }) canvas.draw_axis("y", 0, 100, 0, ticknum=25, ticklabeloptions={ "textsize": 30, "rotate": 70, "anchor": "ne" }, tickfunc=canvas.draw_circle, tickoptions={"fillsize": "1%min"}) canvas.draw_line([10, 10, 50, 90, 90, 10], smooth=True, fillcolor=(222, 0, 0), fillsize="0.5cm") canvas.draw_text("Once upon a time", (50, 20), fillcolor="white", textsize=32) canvas.draw_text("Someplace Near Boulder", (50, 30), textsize=12) canvas.draw_text("There was a reflection", (50, 40), textsize=12, anchor="e") canvas.draw_text("There was a reflection", (50, 40), textsize=12, anchor="w") canvas.draw_text( "Testing text wrap testing textwrap testing. Testing textwrap.", bbox=(40, 60, 60, 80), textsize=17, fillcolor="white", outlinecolor="black", justify="center") for d in ("nw", "n", "ne", "e", "se", "s", "sw", "w"): canvas.draw_text(d, (50, 90), textsize=32, anchor=d) canvas.default_unit = "cm" canvas.draw_circle((50, 50), fillsize="1", fillcolor=(0, 222, 0)) canvas.draw_box((50, 50), fillsize="1", fillcolor=(0, 0, 0, 111)) canvas.draw_triangle((50, 50), fillsize="1", fillcolor=(0, 0, 0, 111)) canvas.default_unit = "in" canvas.draw_circle((50, 50), fillsize="1", fillcolor=(0, 222, 0, 111)) canvas.draw_box((50, 50), fillsize="1", fillcolor=(0, 0, 0, 111)) canvas.draw_triangle((50, 50), fillsize="1", fillcolor=(0, 0, 0, 111)) #miniimg = pyagg.load("C:/Users/kimo/Desktop/ble.png") #canvas.paste(miniimg, bbox=[10,10,130,40], lock_ratio=True, fit=True) #canvas.zoom_bbox(11,0,112,40, lock_ratio=True) #canvas.zoom_bbox(40,10,80,140, lock_ratio=True, fit=True) #canvas.zoom_factor(2) #print canvas.coordspace_units #canvas.zoom_units(1) #print canvas.coordspace_units ## canvas.draw_line([10,10, 50,90, 90,10], ## smooth=True, ## fillcolor=(222,0,0), ## fillsize="2cm") # draw corner coords xy = canvas.pixel2coord(0, 0) canvas.draw_text(str(xy), xy, textsize=33, anchor="nw") xy = canvas.pixel2coord(canvas.width, canvas.height) canvas.draw_text(str(xy), xy, textsize=33, anchor="se") # draw rotated text canvas.draw_text("Rotated", (100, 50), textcolor="black", textsize=32, rotate=15) #canvas.color_remap([(222,0,0),(222,222,0),(0,222,0),(0,222,222),(0,0,222)]) canvas.view() #canvas.rotate(45) #canvas.crop(14,54,55,81) ## canvas.resize(1100,300,lock_ratio=True) ## print canvas.coordspace_bbox ## canvas.draw_line([10,10, 50,90, 90,10], ## smooth=True, ## fillcolor=(222,0,0), ## fillsize="2cm") #canvas.transparency(111) #canvas.transparent_color((222,0,0), tolerance=0.1) #canvas.replace_color((0,0,0), (0,222,211), tolerance=0.2) #canvas.blur(1) #canvas.equalize() #canvas.contrast(2) #canvas.color_tint((0,222,0)) ## def imggen(): ## import os ## import PIL, PIL.Image, PIL.ImageOps ## count = 0 ## for filename in os.listdir("C:/Users/kimo/Pictures/2015-05-22 iPhone,22may2015"): ## if filename.lower().endswith(".jpg"): ## img = PIL.Image.open("C:/Users/kimo/Pictures/2015-05-22 iPhone,22may2015/"+filename) ## yield img ## count += 1 ## if count > 17: ## break ## canvas.grid_paste(imggen(), fit=True) # try normal warp #canvas = pyagg.load("C:/Users/kimo/Desktop/world.gif") #canvas.custom_space(-180,90,180,-90) #canvas.warp(lambda x,y: (x**2,y**2)) ############################# # some geo proj experiments ## import pyproj ## _from = pyproj.Proj("+init=EPSG:4326") ## #_to = pyproj.Proj("+proj=robin") ## #_to = pyproj.Proj("+proj=geos +h=10000000") ## _to = pyproj.Proj("+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +no_defs") ## ## # draw axes ## xs,_ = pyproj.transform(_from, _to, [-179,179], [0,0]) ## xleft,xright = xs ## _,ys = pyproj.transform(_from, _to, [0,0], [89,-89]) ## ytop,ybottom = ys ## print xs,ys,xleft,ytop,xright,ybottom ## canvas.custom_space(xleft,ytop,xright,ybottom) ## canvas.zoom_out(1.2) ## canvas.draw_axis("x", xleft, xright, ybottom, ticknum=10, ticklabeloptions={"rotate":45,"anchor":"ne"}) ## canvas.draw_axis("y", ytop, ybottom, xleft, ticknum=10) ## ## # try warp entire image to a curved geo proj ## # should work (but maybe not since doesnt account for coord differences ## # inside the coordsys except on the edges...?), but so far not working ## def convfunc(x,y): ## try: ## xs,ys = pyproj.transform(_from, _to, [x], [y]) ## newpoint = xs[0],ys[0] ## #if y < -88: print "yes",x,y,newpoint ## except: ## newpoint = (x,y) # bad hack ## # actually, very bad, potentially conaminates and messes up coordys orientation algorithm ## #print "warning, hack, shouldnt happen",newpoint ## if newpoint[0] in (float("inf"),float("nan")) or newpoint[1] in (float("inf"),float("nan")): ## newpoint = (x,y) # bad hack ## return newpoint ## canvas = pyagg.load("C:/Users/kimo/Desktop/world.png").resize(300,150) ## canvas.custom_space(-179.9,89.9,179.9,-89.9) #geographic_space() # no, bc keeps aspect ratio and thus goes out of bounds ## canvas.warp(convfunc) ## import sys ## sys.path.append("C:\Users\kimo\Documents\GitHub\PyCountries") ## import pycountries as pc ## canvas.custom_space(xleft,ytop,xright,ybottom) ## for cntr in pc.Continent("Africa"): ## try: ## geoj = cntr.__geo_interface__ ## if geoj["type"] == "Polygon": ## geoj["coordinates"][0] = [convfunc(*xy) for xy in geoj["coordinates"][0]] ## canvas.draw_polygon(geoj["coordinates"][0], fillcolor="yellow") ## except: pass # geo proj transform grid lines # draw longitude lines to be curved ## for lon in range(-180,180,10): ## ys = range(-90,90,1) ## xs = [lon for _ in ys] ## xs,ys = pyproj.transform(_from, _to, xs, ys) ## ln = zip(xs,ys) ## canvas.draw_line(ln, fillsize="1px", fillcolor=(0,0,0,111)) ## #canvas.custom_space(-180,90,180,-90) ## #canvas.zoom_bbox(-180,90,0,0) canvas.save("__private__/test_output/canvas_tester.png") #view()
if len(pend) > 1 and pend[0] == pend[-1]: finished.append(pending.pop(i)) else: # no correspondance to prev pendings, so create new pending subpoly pend = seg pending.append(pend) seg = nextisec(pts) return finished crazypoly = [Point(randrange(500), randrange(500)) for _ in range(100)] decomp = decompose(crazypoly) print len(crazypoly), len(decomp) import pyagg cnv = pyagg.Canvas(500, 500) ##cnv.draw_polygon(crazypoly, fillcolor=(randrange(222),randrange(222),randrange(222),211)) ##for pt in decomp: ## print pt ## cnv.draw_circle(pt, fillsize=2) for p in decomp: print p cnv.draw_polygon(p, fillcolor=(randrange(222), randrange(222), randrange(222), 211)) cnv.view()
def render_world(crs, savename): import urllib2 import json import pygeoj import pyagg import pyproj import random # load world borders global raw if not raw: raw = urllib2.urlopen( "https://raw.githubusercontent.com/johan/world.geo.json/master/countries.geo.json" ).read() rawdict = json.loads(raw) data = pygeoj.load(data=rawdict) # convert coordinates fromproj = pyproj.Proj("+init=EPSG:4326") toproj = pyproj.Proj(crs.to_proj4()) for feat in data: #if feat.properties['name'] != 'United States of America': continue if feat.geometry.type == "Polygon": feat.geometry.coordinates = [ zip(*pyproj.transform(fromproj, toproj, zip(*ring)[0], zip(*ring)[1])) for ring in feat.geometry.coordinates ] elif feat.geometry.type == "MultiPolygon": feat.geometry.coordinates = [[ zip(*pyproj.transform(fromproj, toproj, zip(*ring)[0], zip(*ring)[1])) for ring in poly ] for poly in feat.geometry.coordinates] feat.geometry.update_bbox() # important to clear away old bbox # get zoom area data.add_all_bboxes() data.update_bbox() bbox = data.bbox ## # to avoid inf bounds and no render in satellite view ## xmins, ymins, xmaxs, ymaxs = zip(*(feat.geometry.bbox for feat in data)) ## inf = float("inf") ## xmaxs = (xmax for xmax in xmaxs if xmax != inf) ## ymaxs = (ymax for ymax in ymaxs if ymax != inf) ## bbox = (min(xmins), min(ymins), max(xmaxs), max(ymaxs)) # set up drawing c = pyagg.Canvas(1000, 1000) c.geographic_space() c.zoom_bbox(*bbox) #c.zoom_out(1.3) # draw countries for feat in data: try: c.draw_geojson(feat.geometry, fillcolor="blue", outlinecolor="white") except: # NOTE: feat.__geo_interface__ is one level too high maybe?? print("unable to draw?", feat.geometry) # draw text of the proj4 string used #c.percent_space() #c.draw_text(crs.to_proj4(), (50,10)) # save c.save("testrenders/" + savename + ".png")