pyagg.canvas module
Defines the PyAgg Canvas class, where most of the PyAgg functinoality is defined.
Functions
def from_image(
img)
Loads a Canvas instance preloaded with the size and pixels of an existing PIL image, from memory.
Parameters:
- img: A PIL image instance.
Returns:
- A Canvas instance.
def load(
filepath)
Loads a Canvas instance preloaded with the size and pixels of an existing image from a file.
Parameters:
- filepath: The filepath of the image file to load.
Returns:
- A Canvas instance.
Classes
class Canvas
An image that knows how to draw on itself and keep track of its coordinate system.
Attributes:
- width: Pixel width of canvas image
- height: Pixel height of canvas image
- ppi: Pixels per inch. Used to calculate pixels needed for real world sizes.
- default_unit: How to interpret sizes given as just a number.
- coordspace_bbox: Bounding box of the canvas coordinate system as a list containing 4 floats [xmin, ymin, xmax, ymax].
- coordspace_width: Width of the canvas coordinate system, as the difference between xmin and xmax.
- coordspace_height: Height of the canvas coordinate system, as the difference between ymin and ymax.
- coordspace_units: The number of coordinate space units per 1 cm screen width.
- coordspace_transform: A list of 6 floats representing the affine transform coefficients used to transform input coordinates to the drawing coordinate system.
Ancestors (in MRO)
Methods
def __init__(
self, width=None, height=None, background=None, mode='RGBA', ppi=300, preset=None)
Creates a new blank canvas image.
Parameters:
- width: Width of the canvas image. Value can be an integer for number of pixels. Value can also be any valid string size: in, cm, or mm. In the latter case uses the ppi setting (pixels per inch) to calculate the pixel width/height equivalent, because pixels are distance agnostic.
- height: Height of the canvas image. Same values as width.
- background (optional): The color of the background image. Value should be an RGB or RGB tuple, or an aggdraw color name that matches the image mode. Defaults to None (transparent).
- mode (optional): any of PIL's image modes, typically 'RGBA' (default) or 'RGB'.
- ppi (optional): Pixels per inch. Defaults to publication quality of 300. Its only effect is that it calculates the correct pixels whenever you use a real world size such as cm, mm, in, or pt. When you use pixel units directly or %, the ppi has no effect. This means that if ppi matters to you, you should initiate the canvas width and height using real world sizes, and draw all sizes using real world sizes as well. Ppi should only be set at initiation time.
- preset (optional): Automatically sets the width and height options based on a template. Valid values are: "A4"
def blur(
self, factor)
def brightness(
self, factor)
def clear(
self)
Clears any drawing done on the canvas, and resets it to its original mode, size, and background.
def color_remap(
self, gradient)
def color_tint(
self, color)
def contrast(
self, factor)
def coord2pixel(
self, x, y)
Transforms a data coordinate to its canvas image pixel position.
Parameters:
- x: X data coordinate.
- y: Y data coordinate.
def copy(
self)
def crop(
self, xmin, ymin, xmax, ymax)
Crop the canvas image to a bounding box defined in pixel coordinates, and the coordinate system will follow. Essentially just an alias for zoom_bbox(), except lock_ratio is set to False by default.
Parameters:
- xmin: The lower bound of the x-axis after the zoom.
- ymin: The lower bound of the y-axis after the zoom.
- xmax: The higher bound of the x-axis after the zoom.
- ymax: The higher bound of the y-axis after the zoom.
Returns:
- In addition to changing the original instance, this method returns the new instance to allow for linked method calls.
def custom_space(
self, xleft, ytop, xright, ybottom, lock_ratio=False)
Defines which areas of the screen represent which areas in the given drawing coordinates. Default is to draw directly with screen pixel coordinates.
Parameters:
- xleft: The x-coordinate to be mapped to the left side of the screen.
- ytop: The y-coordinate to be mapped to the top side of the screen.
- xright: The x-coordinate to be mapped to the right side of the screen.
- ybottom: The y-coordinate to be mapped to the bottom side of the screen.
- lock_ratio (optional): Set to True if wanting to constrain the coordinate space to have the same width/height ratio as the image, in order to avoid distortion. Default is False.
def draw_axis(
self, axis, minval, maxval, intercept, tickpos=None, tickinterval=None, ticknum=5, ticktype='tick', tickoptions={}, ticklabelformat=None, ticklabeloptions={}, noticks=False, noticklabels=False, **kwargs)
Draws an axis line with tickmarks and labels marking positions along the canvas coordinate system.
Parameters:
- axis: Which axis of the coordinate system to draw, either 'x' or 'y' (str)
- minval: At which coordinate along the selected axis the axis line should start.
- maxval: At which coordinate along the selected axis the axis line should end.
- intercept: If drawing a y-axis, where along the opposite x-axis that the line should be positioned (the x-coordinate where the two axes intercept). Opposite if drawing an x-axis.
- tickpos (optional): A list of positions where tick marks should be drawn.
- tickinterval (optional): The coordinate interval between tick marks.
- ticknum (optional): The number of ticks to draw between the minimum and maximum values.
- ticktype (optional): What type of tick to draw, either 'tick' for a small line, or any of the canvas primitive drawing types, eg 'circle', etc. Alternatively a function that takes an xy arg and kwargs to be called for every tick.
- tickoptions (optional): Dictionary of options to be passed to the ticktype drawing method.
- ticklabelformat (optional): Python formatting string or function for converting coordinate values to tick labels. By default auto detects an appropriate formatting based on the axis value range.
- ticklabeloptions (optional): Dictionary of options to be passed to the draw_text() tick labeling method.
- noticks (optional): Disables drawing any tick marks.
- noticklabels (optional): Disables drawing any tick mark labels.
- kwargs (optional): Any additional keyword args are passed on as options to the draw_line() method that renders the axis line.
def draw_box(
self, xy=None, bbox=None, flatratio=1.0, **options)
Draw a square, equisized or rectangular. Either specified with xy and flatratio, or with a bbox.
Parameters:
- xy (optional): Xy center coordinate to place the square.
- bbox (optional): Bounding box of the flattened rectangle instead of xy coordinate.
- flatratio (optional): The ratio of the rectangle height to width. A normal square is given with 1.0 (default) and a half-flat rectangle with 0.5.
- options (optional): Keyword args dictionary of draw styling options.
def draw_circle(
self, xy=None, bbox=None, flatratio=1, **options)
Draw a circle, normal or flattened. Either specified with xy and flatratio, or with a bbox.
Parameters:
- xy (optional): Xy center coordinate to place the circle.
- bbox (optional): Bounding box of the flattened circle instead of xy coordinate.
- flatratio (optional): The ratio of the circle height to width. A normal circle is given with 1.0 (default) and a half-flat circle with 0.5.
- options (optional): Keyword args dictionary of draw styling options.
def draw_geojson(
self, geojobj, **options)
Draws a shape based on the GeoJSON format.
Parameters:
- geojobj: Takes a GeoJSON dictionary or object that has the __geo_interface__ attribute. Must be a geometry type, or a feature type with a geometry attribute.
- options: Keyword args dictionary of draw styling options.
def draw_gradient(
self, line, gradient, width, steps=100)
def draw_grid(
self, xinterval, yinterval, **kwargs)
def draw_line(
self, coords, smooth=False, **options)
Connect a series of coordinate points with one or more lines. Outline does not work with this method.
Parameters:
- coords: A list of coordinates for the linesequence.
- smooth (optional): If True, smooths the lines by drawing quadratic bezier curves between midpoints of each line segment. Default is False.
- options (optional): Keyword args dictionary of draw styling options.
def draw_pie(
self, xy, startangle, endangle, **options)
Draw a piece of pie.
Parameters:
- xy: Xy center coordinate to place the pie origin.
- startangle: Degree angle to start the pie.
- endangle: Degree angle to end the pie.
- options (optional): Keyword args dictionary of draw styling options.
def draw_polygon(
self, coords, holes=[], **options)
Draw polygon and holes with color fill. Holes must be counterclockwise.
Parameters:
- coords: A list of coordinates for the polygon exterior.
- holes (optional): A list of one or more polygon hole coordinates, one for each hole. Defaults to no holes.
- options (optional): Keyword args dictionary of draw styling options.
def draw_text(
self, text, xy=None, bbox=None, rotate=None, **options)
Draws basic text.
Parameters:
- text: The text string to write.
- xy (optional): The xy location to write the text.
- bbox (optional): The bounding box into which the text should fit instead of xy location. If specified, wraps text where necessary and calculates optimal font size to fit inside the box, ignoring any user specified font size.
- options (optional): Keyword args dictionary of text styling options. This includes the usual fillcolor/size and outlinecolor/width and some additional ones. Font is used with the xy argument and can be the name, filename, or filepath of a font. Anchor is used with the xy argument and can be any compass direction n,ne,e,se,s,sw,w,nw, or center. Justify is used with the bbox argument and can be any left,right,center direction. Padx is used with the bbox argument or when using xy with fillcolor or outlinecolor and specifies the percent x padding between the text and the box. Pady is used with the bbox argument or when using xy with fillcolor or outlinecolor and specifies the percent y padding between the text and the box.
def draw_triangle(
self, xy=None, bbox=None, flatratio=1.0, **options)
Draw a triangle, equiangled or otherwise. Either specified with xy and flatratio, or with a bbox.
Parameters:
- xy (optional): Xy center coordinate to place the triangle.
- bbox (optional): Bounding box of the flattened triangle instead of xy coordinate.
- flatratio (optional): The ratio of the triangle height to width. A normal triangle is given with 1.0 (default) and a half-flat triangle with 0.5.
- options (optional): Keyword args dictionary of draw styling options.
def equalize(
self)
def flip(
self, xflip=True, yflip=False)
Flip the canvas image horizontally or vertically (center-anchored), and the coordinate system will follow.
Parameters:
- xflip (optional): Flips the image horizontally if set to True. Default is True.
- yflip (optional): Flips the image vertically if set to True. Default is False.
Returns:
- In addition to changing the original instance, this method returns the new instance to allow for linked method calls.
def fraction_space(
self)
Convenience method for setting the coordinate space to fractions, so the user can easily draw using relative fractions (0-1) of image.
def geographic_space(
self)
Convenience method for setting the coordinate space to geographic, so the user can easily draw coordinates as lat/long of world, from -180 to 180 x coordinates, and -90 to 90 y coordinates. Also locks the aspect ratio to fit the entire coordinate space inside the image without geographic distortion.
def get_image(
self)
Retrieves the canvas image along with any drawing updates.
Returns:
- A PIL image.
def get_tkimage(
self)
Retrieves a Tkinter compatible image along with any drawing updates.
Returns:
- A Tkinter PhotoImage image.
def grid_paste(
self, imgs, columns=None, rows=None, colfirst=True, lock_ratio=True, fit=True)
def invert(
self)
def measure_dist(
self, fromxy, toxy)
Returns euclidean distance between two xy point tuples, assuming they are linear cartesian coordinates.
Parameters:
- fromxy: Data coordinate point to measure from.
- toxy: Data coordinate point to measure to.
def move(
self, xmove, ymove)
Move/offset the canvas image in pixels or other units, and the coordinate system will follow.
Parameters:
- xmove: Moves/offsets the image horizontally. Can be specified with any unit with a string representation. Otherwise defaults to pixels.
- ymove: Moves/offsets the image vertically. Can be specified with any unit with a string representation. Otherwise defaults to pixels.
Returns:
- In addition to changing the original instance, this method returns the new instance to allow for linked method calls.
def paste(
self, image, xy=(0, 0), bbox=None, lock_ratio=True, fit=True, anchor='nw', outlinewidth=None, outlinecolor='black')
Paste a PIL image or PyAgg canvas onto a given location in the Canvas.
Parameters:
- image: PIL image or PyAgg canvas to paste.
- xy: An xy point tuple of the location to paste the northwest corner of the image. Can be specified with any unit with a string representation. Otherwise defaults to pixels.
- bbox: ...
- lock_ratio: ...
- fit: ...
- anchor: What part of the image to anchor at the xy point. Can be any compass direction n,ne,e,se,s,sw,w,nw, or center.
- outlinewidth: ...
- outlinecolor: ...
Returns:
- In addition to changing the original instance, this method returns the new instance to allow for linked method calls.
def percent_space(
self)
Convenience method for setting the coordinate space to percentages, so the user can easily draw coordinates as percentage (0-100) of image.
def pixel2coord(
self, x, y)
Transforms a pixel location on the image to its position in the canvas coordinate system.
Parameters:
- x: X image pixel coordinate.
- y: Y image pixel coordinate.
def pixel_space(
self)
Convenience method for setting the coordinate space to pixels, so the user can easily draw directly to image pixel positions.
def replace_color(
self, color, newcolor, tolerance=0)
def resize(
self, width, height, lock_ratio=False, fit=True)
Resize canvas image to new width and height in pixels or other units, and the coordinate system will follow, so that each corner in the old image is equivalent to each corner in the new image.
Parameters:
- width: Width of the new image. Can be specified with any unit with a string representation. Otherwise defaults to pixels.
- height: Height of the new image. Can be specified with any unit with a string representation. Otherwise defaults to pixels.
- lock_ratio (optional): Whether to modify the given sizes to preserve the width/height ratio of the original image. Default is False.
Returns:
- In addition to changing the original instance, this method returns the new instance to allow for linked method calls.
def rotate(
self, degrees, expand=True)
Rotate the canvas image in degree angles, and the coordinate system will follow.
Parameters:
- degrees: Degree angles to rotate. 0 degrees faces upwards and increases clockwise.
Returns:
- In addition to changing the original instance, this method returns the new instance to allow for linked method calls.
def save(
self, filepath)
Saves the canvas image to a file.
Parameters:
- filepath: The filepath to save the image, including the file type extension. Can be saved to any image type supported by PIL.
def set_default_unit(
self, unit)
Sets the default unit for drawing sizes etc.
Parameters:
- unit: Can be real world units (cm, mm, in, pt), percent of width or height (%w or %h), or percent of minimum or maximum side (%min or %max). Default is percent of width.
def sharpen(
self, factor)
def transparency(
self, alpha)
def transparent_color(
self, color, alpha=0, tolerance=0)
def update_drawer_img(
self)
Updates any image changes to the drawer, and reapplies the transform to the new image size. Mostly used internally, but can be useful if you apply any PIL operations directly to the canvas image (the .img attribute).
def view(
self)
Creates a Tkinter application that packs the canvas image in order to view what the canvas image looks like.
def zoom_bbox(
self, xmin, ymin, xmax, ymax, lock_ratio=True, fit=True)
Essentially the same as using coord_space(), but takes a bbox in min/max format instead, converting to left/right/etc behind the scenes so that axis directions are preserved. Moreover, the existing image is zoomed as well.
Parameters:
- xmin: The lower bound of the x-axis after the zoom.
- ymin: The lower bound of the y-axis after the zoom.
- xmax: The higher bound of the x-axis after the zoom.
- ymax: The higher bound of the y-axis after the zoom.
- lock_ratio: Preserve the aspect ratio of the original image/coordsys.
def zoom_factor(
self, factor, center=None)
Zooms in or out n times of previous bbox. Useful when the zoom is called programmatically and it is not certain which way the zoom will go.
Parameters:
- factor: Positive values > 1 for in-zoom, negative < -1 for out-zoom.
- center (optional): xy coordinate tuple to center/offset the zoom. Defauls to middle of the bbox.
def zoom_in(
self, factor, center=None)
Zooms inwards n times of previous bbox. Same as zoom_factor() with a positive value.
Parameters:
- factor: Zoom in factor, 1 or higher.
- center (optional): xy coordinate tuple to center/offset the zoom. Defauls to middle of the bbox.
def zoom_out(
self, factor, center=None)
Zooms outwards n times of previous bbox. Same as zoom_factor() with a negative value.
Parameters:
- factor: Zoom out factor, 1 or higher.
- center (optional): xy coordinate tuple to center/offset the zoom. Defauls to middle of the bbox.
def zoom_units(
self, units, center=None)
Zoom in or out based on how many units per cm to have at the new zoom level.
Parameters:
- units: how many coordinate units per screen cm at the new zoom level.
- center (optional): xy coordinate tuple to center/offset the zoom. Defauls to middle of the bbox.
class Gradient