### Drawbot Font Management and Installation Source: https://context7.com/typemytype/drawbot/llms.txt Demonstrates dynamic font management in Drawbot, including listing all installed fonts, filtering by character support, installing custom fonts from files, and querying font properties like file path and character/glyph support. It shows how to set fonts for text rendering. ```python import drawBot as db db.size(800, 600) # List all installed fonts all_fonts = db.installedFonts() print(f"Total fonts: {len(all_fonts)}") print(f"First 5 fonts: {all_fonts[:5]}") # Filter fonts by character support arabic_fonts = db.installedFonts(supportsCharacters="مرحبا") print(f"Fonts supporting Arabic: {len(arabic_fonts)}") # Install custom font from file font_name = db.installFont("path/to/customfont.ttf") print(f"Installed font: {font_name}") db.font(font_name, 48) db.text("Using custom font", (50, 500)) # Query font properties db.font("Helvetica", 100) print(f"Font file: {db.fontFilePath()}") print(f"Font contains 'A': {db.fontContainsCharacters('A')}") print(f"Font contains glyph 'A.alt': {db.fontContainsGlyph('A.alt')}") ``` -------------------------------- ### DrawBot: Canvas Setup and Image Export Source: https://context7.com/typemytype/drawbot/llms.txt Sets up a canvas with specified dimensions, draws a rectangle and text, and exports the output to PDF, PNG, and SVG formats. It also demonstrates how to query the canvas dimensions. ```python import drawBot as db # Create a 500x500 pixel canvas db.size(500, 500) # Set fill color (RGB values from 0 to 1) db.fill(1, 0, 0) # Draw a rectangle db.rect(50, 50, 400, 400) # Set text properties db.fill(1, 1, 1) db.font("Helvetica-Bold", 48) db.text("DrawBot", (100, 225)) # Save to multiple formats db.saveImage("~/Desktop/output.pdf") db.saveImage("~/Desktop/output.png", imageResolution=300) db.saveImage("~/Desktop/output.svg") # Query canvas dimensions print(f"Width: {db.width()}, Height: {db.height()}") ``` -------------------------------- ### Font Management - Install Font Source: https://github.com/typemytype/drawbot/blob/master/docs/content/text/drawingText.md Installs a font from a given file path for the current DrawBot process. The PostScript font name is returned, which can then be used to set the font. ```APIDOC ## installFont(path) ### Description Install a font with a given path and the postscript font name will be returned. The postscript font name can be used to set the font as the active font. Fonts are installed only for the current process and will be automatically uninstalled when the script is done. ### Method N/A (Function signature provided) ### Endpoint N/A (Function signature provided) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Example usage (not a direct API request) path = "path/to/your/font.otf" fontName = installFont(path) font(fontName, 100) text("Sample Text", (10, 10)) ``` ### Response #### Success Response (200) - **fontName** (string) - The PostScript name of the installed font. ``` -------------------------------- ### guidedFilter Source: https://github.com/typemytype/drawbot/blob/master/docs/content/image/imageObject.md Upsamples a small image to the size of a guide image, using the guide's content to preserve detail. ```APIDOC ## guidedFilter ### Description Upsamples a small image to the size of the guide image using the content of the guide to preserve detail. ### Method (Not specified, assumed to be part of an image processing pipeline) ### Endpoint (Not specified, assumed to be called on an image object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **guideImage** (Image object) - Required - A larger image to use as a guide. - **radius** (float) - Optional - The distance from the center of the effect. Defaults to 1.0. - **epsilon** (float) - Optional - A small value to prevent division by zero or other numerical issues. Defaults to 0.0001. ### Request Example ```json { "guideImage": "", "radius": 2.0, "epsilon": 0.00001 } ``` ### Response #### Success Response (200) (Not specified, assumes the image object is modified in place or returned) #### Response Example (Not specified) ``` -------------------------------- ### DrawBot: Canvas Setup and Basic Shapes Source: https://github.com/typemytype/drawbot/blob/master/docs/content/quickReference.md Sets the canvas size and demonstrates drawing basic shapes like rectangles, ovals, and polygons using DrawBot's Python API. It also shows how to create and draw paths, including curves. ```python # DrawBot reference # set a size for the canvas size(500, 500) # using the functions width, height and pageCount print("width:", width()) print("height:", height()) print("pageCount:", pageCount()) # simple shapes # draw rect x, y, width, height rect(10, 10, 100, 100) # draw oval x, y, width, height ovel(10, 120, 100, 100) ovel(120, 120, 100, 100) # draw polygon polygon((10, 250), (100, 250), (100, 400), (50, 300), close=False) # create path newPath() # move to point moveTo((300, 100)) lineTo((400, 100)) # first control point (x1, y1) # second control point (x2, y2) # end point (x3, y3) curveTo((450, 150), (450, 250), (400, 300)) lineTo((300, 300)) # close the path closePath() # draw the path drawPath() ``` -------------------------------- ### Python Loops: Basic and Nested Iterations Source: https://github.com/typemytype/drawbot/blob/master/docs/content/courseware.md Demonstrates various ways to use loops in Python, including simple for loops, nested loops for multi-dimensional iteration, and loops with counters. These examples showcase iteration over ranges and manipulating loop variables. ```python print("hello") # also: use the tab key to manually # indent. There are shortcuts to indent # or dedent blocks of code: cmd-[ print("loop over some numbers:") for item in range(10): print(item) print("loop over some numbers, doing 'math':") for i in range(10): print(i, i * 0.5) print("nested loops:") for x in range(1, 5): # outer loop print("---") for y in range(x, x + 5): # inner loop print(x, y, x * y) print("three loops:") for x in range(2): for y in range(2): for z in range(2): print(x, y, z) print("three loops with a counter:") count = 1 for x in range(2): for y in range(2): for z in range(2): print(x, y, z, count) count = count + 1 # alternate spelling: #count += 1 ``` -------------------------------- ### Font Management - List Installed Fonts Source: https://github.com/typemytype/drawbot/blob/master/docs/content/text/drawingText.md Retrieves a list of all fonts installed on the system, with an option to filter by fonts that support a specific set of characters. ```APIDOC ## installedFonts(supportsCharacters=None) ### Description Returns a list of all installed fonts. Optionally a string with supportsCharacters can be provided, the list of available installed fonts will be filtered by support of these characters. ### Method N/A (Function signature provided) ### Endpoint N/A (Function signature provided) ### Parameters #### Path Parameters None #### Query Parameters - **supportsCharacters** (string) - Optional - A string of characters to filter installed fonts by their support. #### Request Body None ### Request Example ```python # Example usage (not a direct API request) all_fonts = installedFonts() cyrillic_fonts = installedFonts(supportsCharacters="абв") print(all_fonts) print(cyrillic_fonts) ``` ### Response #### Success Response (200) - **fonts** (list of strings) - A list of font names. ``` -------------------------------- ### List Installed Fonts Source: https://github.com/typemytype/drawbot/blob/master/docs/content/text/drawingText.md Retrieves a list of all fonts currently installed on the system. Optionally, this list can be filtered to include only fonts that support a specific set of characters, provided as a string. ```python installedFonts(supportsCharacters=None) ``` -------------------------------- ### Drawbot Image Operations Source: https://context7.com/typemytype/drawbot/llms.txt Provides examples for loading, displaying, and querying image properties using Drawbot. It covers drawing images at specific positions, with alpha transparency, scaled to dimensions, and how to retrieve image dimensions, resolution, and pixel color. It also shows how to handle multi-page documents (PDFs, GIFs) and use ImageObjects. ```python import drawBot as db db.size(1000, 800) # Load and draw image image_path = "path/to/image.jpg" # Can also use URLs: "https://example.com/image.png" # Draw at position with default size db.image(image_path, (50, 500)) # Draw with alpha transparency db.image(image_path, (250, 500), alpha=0.5) # Draw scaled to specific size db.image(image_path, (450, 500), width=200, height=150) # Query image properties width, height = db.imageSize(image_path) print(f"Image dimensions: {width} x {height}") resolution = db.imageResolution(image_path) print(f"Image resolution: {resolution} DPI") # For PDFs and animated GIFs page_count = db.numberOfPages("document.pdf") print(f"PDF has {page_count} pages") # Draw specific page from PDF or GIF db.image("document.pdf", (50, 250), pageNumber=2) # Sample pixel color from image color = db.imagePixelColor(image_path, (100, 100)) if color: r, g, b, a = color print(f"Pixel color at (100,100): R={r}, G={g}, B={b}, A={a}") # Use sampled color db.fill(r, g, b, a) db.rect(700, 300, 100, 100) # ImageObject for advanced manipulation img = db.ImageObject() with img: db.size(200, 200) db.fill(1, 0, 0) db.oval(0, 0, 200, 200) # Use ImageObject as image source db.image(img, (700, 500)) ``` -------------------------------- ### Python Variable Assignment and Naming Rules Source: https://github.com/typemytype/drawbot/blob/master/docs/content/courseware.md Explains how to declare and use variables in Python, including basic assignment, variable naming conventions (allowed characters, case sensitivity), and the concept of rebinding variables. It also demonstrates valid and invalid variable name examples. ```python a = 12 b = 15 c = a * b CAP = "a string" print(c) print(CAP) # variable names cannot start with a # number: #1a = 12 # variable names can contain numbers, # just not at the start: a1 = 12 # underscores are allowed: _a = 12 a_ = 13 # a-z A-Z 0-9 _ # everything is an object # this "rebinds" the name 'a' to a new # object: a = a + 12 # variable names are case sensitive # meaning that: x = 12 # is a different variable from X = 13 print(x) print(X) y = 102 # so this is an error: print(Y) ``` -------------------------------- ### Text Layout - Line Baselines Source: https://github.com/typemytype/drawbot/blob/master/docs/content/text/drawingText.md Calculates the starting coordinates (x, y) for each line of text within a defined bounding box, with optional text alignment. ```APIDOC ## textBoxBaselines(txt, box, align=None) ### Description Returns a list of x, y coordinates indicating the start of each line for a given text in a given box. A box could be a (x, y, w, h) or a bezierPath object. Optionally an alignment can be set. Possible align values are: “left”, “center”, “right” and “justified”. ### Method N/A (Function signature provided) ### Endpoint N/A (Function signature provided) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Example usage (not a direct API request) lines = textBoxBaselines("Some long text that needs wrapping", (50, 50, 200, 100), align="justified") print(lines) ``` ### Response #### Success Response (200) - **lines** (list of tuples) - A list where each tuple represents the (x, y) coordinate for the start of a text line. ``` -------------------------------- ### Drawbot Shapes: Rectangles and Ovals Source: https://github.com/typemytype/drawbot/blob/master/docs/content/courseware.md Provides examples of drawing basic shapes like rectangles and ovals using the Drawbot library's functions `rect()` and `oval()`. It demonstrates drawing individual shapes and using loops to create patterns. ```python # draw a rectangle # rect(x, y, width, height) rect(20, 50, 100, 200) rect(130, 50, 100, 200) oval(240, 50, 100, 200) oval(20, 250, 100, 100) oval(130, 250, 100, 100) rect(240, 250, 100, 100) for x in range(20, 300, 50): rect(x, 370, 40, 40) for x in range(20, 300, 50): if random() > 0.5: rect(x, 420, 40, 40) else: oval(x, 420, 40, 40) ``` -------------------------------- ### Drawbot Canvas Transformations Source: https://context7.com/typemytype/drawbot/llms.txt Apply various canvas transformations including translation, rotation, scaling, and skewing using Drawbot. This example uses a helper function to draw a shape and demonstrates transformations applied independently and combined, including manual transformation matrix usage. ```python import drawBot as db db.size(800, 800) # Helper function to draw a reference shape def draw_shape(): db.fill(0.8, 0.2, 0.2) db.rect(0, 0, 100, 100) db.fill(0) db.oval(90, 90, 20, 20) # Original position db.fill(0.9, 0.9, 0.9) db.rect(50, 650, 100, 100) # Translation with db.savedState(): db.translate(200, 650) draw_shape() # Rotation (degrees, around center point) with db.savedState(): db.translate(450, 700) db.rotate(45, center=(50, 50)) draw_shape() # Scaling with db.savedState(): db.translate(50, 450) db.scale(1.5, 1.0) draw_shape() # Scaling from center with db.savedState(): db.translate(250, 450) db.scale(1.5, center=(50, 50)) draw_shape() # Skewing with db.savedState(): db.translate(450, 450) db.skew(20, 10) draw_shape() # Combined transformations with db.savedState(): db.translate(400, 200) db.rotate(30) db.scale(1.2, 0.8) draw_shape() # Manual transformation matrix with db.savedState(): db.translate(100, 100) db.transform((1, 0.2, 0.3, 1, 0, 0)) # Custom affine transform draw_shape() ``` -------------------------------- ### Drawbot FormattedString for Rich Text Source: https://context7.com/typemytype/drawbot/llms.txt Create and draw styled text with mixed formatting using Drawbot's FormattedString objects. This example demonstrates applying different fonts, sizes, colors, tracking, and drawing text within a defined box, including checking for overflow. ```python import drawBot as db db.size(800, 600) # Create a formatted string with mixed styles fs = db.FormattedString() fs.font("Helvetica-Bold") fs.fontSize(48) fs.fill(1, 0, 0) fs.append("Red Bold ") fs.font("Times-Italic") fs.fontSize(36) fs.fill(0, 0, 1) fs.append("Blue Italic ") fs.font("Courier") fs.fontSize(32) fs.fill(0, 0.5, 0) fs.tracking(5) fs.append("Green Tracked") # Draw the formatted string db.text(fs, (50, 450)) # Use FormattedString in text box fs2 = db.FormattedString() fs2.fontSize(24) fs2.fill(0) fs2.append("This is ") fs2.font("Helvetica-Bold") fs2.fill(0.8, 0, 0) fs2.append("mixed ") fs2.font("Helvetica") fs2.fill(0) fs2.append("formatting in a box.") db.textBox(fs2, (50, 250, 400, 150)) # Check for text overflow overflow_text = db.textOverflow(fs2, (50, 250, 200, 50)) if overflow_text: print("Text overflowed!") ``` -------------------------------- ### Python String Manipulation and Concatenation Source: https://github.com/typemytype/drawbot/blob/master/docs/content/courseware.md Illustrates string handling in Python, including creating strings with different quote types, concatenating strings, repeating strings, and handling non-ASCII characters. It also shows an example of an error caused by multiplying a string by a float. ```python print('this is a so called "string"') print("this is a so called 'string'") print("this is a so called \"string\"") print("one string " + "another string") a = "one string" b = "another string" print(a + " " + b) print("many " * 10) print("non-ascii should generally work:") print("Åbenrå © Ђ ק") print("and now an error:") print("many " * 10.0) # string multiplication really wants an # integer number; a float that happens to # be a whole number is not good enough ``` -------------------------------- ### Drawbot: Construct and Draw a Closed Bezier Path Source: https://github.com/typemytype/drawbot/blob/master/docs/content/shapes/drawingPath.md Illustrates the process of creating a new path, defining its shape using moveTo, lineTo, and curveTo, closing the path with closePath, and finally rendering it using drawPath. This example shows a path with straight lines and a Bezier curve. ```python # create a new empty path newPath() # set the first oncurve point moveTo((100, 100)) # line to from the previous point to a new point lineTo((100, 900)) lineTo((900, 900)) # curve to a point with two given handles curveTo((900, 500), (500, 100), (100, 100)) # close the path closePath() # draw the path drawPath() ``` -------------------------------- ### Get Text Line Start Coordinates in a Box Source: https://github.com/typemytype/drawbot/blob/master/docs/content/text/drawingText.md Calculates and returns the starting x, y coordinates for each line of text within a specified bounding box. The box can be defined as a tuple (x, y, w, h) or a bezierPath object. Text alignment (left, center, right, justified) is an optional parameter. ```python textBoxBaselines(txt, box, align=None) ``` -------------------------------- ### DrawBot: Text Rendering and Formatting Source: https://github.com/typemytype/drawbot/blob/master/docs/content/quickReference.md Shows how to render text using DrawBot, including setting font, size, fill color, stroke color, and stroke width. It also demonstrates using `textBox` for multi-line text and measuring text dimensions. ```python newPage() print("pageCount:", pageCount()) text("Hello World", (10, 10)) fontSize(100) fill(1, 0, 0) stroke(0) strokeWidth(5) text("Hello World", (10, 20)) font("Times-Italic", 25) fill(0, .5, 1) stroke(None) textBox("Hello World " * 100, (10, 150, 300, 300)) print("textSize:", textSize("Hallo")) ``` -------------------------------- ### DrawBot: Image Placement and Color Fills Source: https://github.com/typemytype/drawbot/blob/master/docs/content/quickReference.md Demonstrates how to place images on the canvas with transparency and apply various fill colors, including grayscale, RGB, and RGBA. It also shows how to set stroke colors and widths. ```python newPage() # image: path, (x, y), alpha image("https://github.com/typemytype/drawbot/raw/master/docs/content/assets/drawBot.jpg", (10, 10), .5) newPage() print("pageCount:", pageCount()) # colors # fill(r, g, b) # fill(r, g, b, alpha) # fill(grayvalue) # fill(grayvalue, alpha) # fill(None) fill(.5) rect(10, 10, 100, 100) fill(1, 0, 0) rect(10, 120, 100, 100) fill(0, 1, 0, .5) ovel(50, 50, 100, 100) fill(None) # stroke(r, g, b) # stroke(r, g, b, alpha) # stroke(grayvalue) # stroke(grayvalue, alpha) # stroke(None) strokeWidth(8) stroke(.8) rect(200, 10, 100, 100) stroke(.1, .1, .8) rect(200, 120, 100, 100) strokeWidth(20) stroke(1, 0, 1, .5) ovel(250, 50, 100, 100) ``` -------------------------------- ### Initialize and Draw with ImageObject in Python Source: https://github.com/typemytype/drawbot/blob/master/docs/content/image/imageObject.md Demonstrates how to create an ImageObject, draw within its context using nested size(), fill(), rect(), and text() calls, and then draw the ImageObject onto the main canvas. It also shows how to apply filters like gaussianBlur() and retrieve image offset. ```python size(550, 300) # initiate a new image object im = ImageObject() # draw in the image # the 'with' statement will create a custom context # only drawing in the image object with im: # set a size for the image size(200, 200) # draw something fill(1, 0, 0) rect(0, 0, width(), height()) fill(1) fontSize(30) text("Hello World", (10, 10)) # draw in the image in the main context image(im, (10, 50)) # apply some filters im.gaussianBlur() # get the offset (with a blur this will be negative) x, y = im.offset() # draw in the image in the main context image(im, (300+x, 50+y)) ``` -------------------------------- ### DrawBot: Canvas Transformations (Scale, Rotate, Skew) Source: https://github.com/typemytype/drawbot/blob/master/docs/content/quickReference.md Illustrates the use of canvas transformations in DrawBot, including saving and restoring the drawing state. It demonstrates how to apply scaling, rotation, and skewing to subsequent drawing operations. ```python newPage() # canvas transformations print("pageCount:", pageCount()) fill(None) stroke(0) strokeWidth(3) save() rect(10, 10, 100, 100) scale(2) rect(10, 10, 100, 100) restore() save() rotate(30) rect(10, 10, 100, 100) restore() save() skew(30) rect(10, 10, 100, 100) restore() ``` -------------------------------- ### Install and Use a Font Temporarily Source: https://github.com/typemytype/drawbot/blob/master/docs/content/text/drawingText.md Installs a font from a given file path for the current process only. It returns the postscript font name, which can then be used to set the active font for drawing text. The font is automatically uninstalled when the script finishes. Note: This function is deprecated; use the font path directly. ```python # set the path to a font file path = "path/to/font/file.otf" # install the font fontName = installFont(path) # set the font font(fontName, 200) # draw some text text("Hello World", (10, 10)) # uninstall font uninstallFont(path) ``` -------------------------------- ### Set Radial Gradient Fill in Drawbot Source: https://github.com/typemytype/drawbot/blob/master/docs/content/color/fill.md Sets a radial gradient as the fill color for subsequent shapes. Requires start and end points, a list of colors (as RGB tuples), and optionally color locations, start radius, and end radius. This fill setting overrides any previously set solid fill color. ```python radialGradient( (300, 300), # startPoint (600, 600), # endPoint [(1, 0, 0), (0, 0, 1), (0, 1, 0)], # colors [0, .2, 1], # locations 0, # startRadius 500 # endRadius ) # draw a rectangle rect(10, 10, 980, 980) ``` -------------------------------- ### DrawBot: Text Rendering and Typography Source: https://context7.com/typemytype/drawbot/llms.txt Demonstrates rendering text with DrawBot, including basic text drawing, alignment options (center, right), and text boxes with automatic wrapping. It also shows how to set fonts, sizes, and fill colors for text. ```python import drawBot as db db.size(1000, 800) # Basic text drawing db.font("Helvetica-Bold", 72) db.fill(0, 0, 0) db.text("Hello DrawBot", (50, 700)) # Text with alignment db.font("Times-Italic", 48) db.fill(0.5, 0, 0.5) db.text("Centered", (500, 600), align="center") db.text("Right Aligned", (950, 600), align="right") # Text box with wrapping db.font("Georgia", 24) db.fill(0.2, 0.2, 0.2) lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " * 5 db.textBox(lorem, (50, 350, 400, 200)) ``` -------------------------------- ### Draw Oval using oval() Source: https://github.com/typemytype/drawbot/blob/master/docs/content/shapes/primitives.md Draws an oval on the canvas. Requires x and y coordinates for the starting point, and width (w) and height (h) for dimensions. ```python # draw an oval # x y w h ovel(100, 100, 800, 800) ``` -------------------------------- ### ImageObject Class and Basic Methods Source: https://github.com/typemytype/drawbot/blob/master/docs/content/image/imageObject.md Details on the ImageObject class initialization and fundamental methods for managing image properties and state. ```APIDOC ## ImageObject Class and Basic Methods ### Description Represents an image object that can be manipulated with various filters and drawing operations. Supports multiple image formats and NSImage objects. ### Initialization * **ImageObject**(path=None) * Initializes a new ImageObject. Optionally opens an image from the specified file path. ### Methods * **size(width, height)** * Sets or returns the size of the image. * **offset()** * Returns the offset of the image, which may change due to filters. * **clearFilters()** * Removes all applied filters from the image. * **open(path)** * Opens an image from the specified file path. * **copy()** * Returns a duplicate of the current ImageObject. * **lockFocus()** * Sets the drawing focus to this image. * **unlockFocus()** * Removes the drawing focus from this image. ### Request Example ```python im = ImageObject() im.size(200, 200) print(im.size()) ``` ### Response * **size()** returns a tuple (width, height). * **offset()** returns a tuple (x, y). ### Response Example ```json { "size": [200, 200], "offset": [0, 0] } ``` ``` -------------------------------- ### Draw Rectangle using rect() Source: https://github.com/typemytype/drawbot/blob/master/docs/content/shapes/primitives.md Draws a rectangle on the canvas. Requires x and y coordinates for the starting point, and width (w) and height (h) for dimensions. ```python # draw a rectangle # x y w h rect(100, 100, 800, 800) ``` -------------------------------- ### DrawBot: Clipping Paths and Saving Images Source: https://github.com/typemytype/drawbot/blob/master/docs/content/quickReference.md Demonstrates how to use `clipPath` to restrict drawing to a specific region defined by a Bezier path. It also shows how to save the final output to various image formats like PDF, PNG, SVG, and MP4. ```python newPage() save() path = BezierPath() path.oval(20, 20, 300, 100) clipPath(path) fill(1, 0, 0, .3) rect(10, 10, 100, 100) fontSize(30) text("Hello World", (50, 80)) restore() valentine(200, 20, 50, 50) saveImage(u"~/Desktop/drawBotTest.pdf") saveImage(u"~/Desktop/drawBotTest.png") saveImage(u"~/Desktop/drawBotTest.svg") saveImage(u"~/Desktop/drawBotTest.mp4") print("Done") ``` -------------------------------- ### Set Line Height in Drawbot Source: https://github.com/typemytype/drawbot/blob/master/docs/content/text/textProperties.md Adjusts the vertical spacing between lines of text. The example sets line height, font size, and draws text in a box. ```python # set line height lineHeight(150) # set font size fontSize(60) # draw text in a box textBox("Hello World " * 10, (100, 100, 800, 800)) ``` -------------------------------- ### Page Manipulation and Iteration in Python Source: https://github.com/typemytype/drawbot/blob/master/docs/content/canvas/pages.md Demonstrates creating multiple pages with different sizes and colors, then iterating through them. It shows how to use `newPage()`, `size()`, `fill()`, `rect()`, `pages()`, and the `with` statement to access and draw on specific pages. Text is added to a page using `text()` and `fontSize()`. ```python # set a size size(200, 200) # draw a rectangle rect(10, 10, 100, 100) # create a new page newPage(200, 300) # set a color fill(1, 0, 1) # draw a rectangle rect(10, 10, 100, 100) # create a new page newPage(200, 200) # set a color fill(0, 1, 0) # draw a rectangle rect(10, 10, 100, 100) # get all pages allPages = pages() # count how many pages are available print(len(allPages)) # use the `with` statement # to set a page as current context with allPages[1]: # draw into the selected page fontSize(30) text("Hello World", (10, 150)) # loop over allpages for page in allPages: # set the page as current context with page: # draw an oval in each of them oval(110, 10, 30, 30) ``` -------------------------------- ### Set Character Tracking in Drawbot Source: https://github.com/typemytype/drawbot/blob/master/docs/content/text/textProperties.md Modifies the spacing between characters by adding an absolute number of points. Can be enabled or disabled by setting the value to None. The example demonstrates enabling and disabling tracking. ```python size(1000, 350) # set tracking tracking(100) # set font size fontSize(100) # draw some text text("hello", (100, 200)) # disable tracking tracking(None) # draw some text text("world", (100, 100)) ``` -------------------------------- ### OpenType Features in Drawbot Source: https://github.com/typemytype/drawbot/blob/master/docs/content/text/textProperties.md Enables specific OpenType features for fonts, such as ligatures, contextual alternates, and number forms. Features can be reset to default. Example shows enabling 'onum' and 'smcp', then resetting. ```python newPage(1000, 300) # set a font font("Didot") # set the font size fontSize(50) # create a string someTxt = "aabcde1234567890" # draw the string text(someTxt, (100, 220)) # enable some OpenType features openTypeFeatures(onum=True, smcp=True) # draw the same string text(someTxt, (100, 150)) # reset defaults openTypeFeatures(resetFeatures=True) # the same string again, back to default features text(someTxt, (100, 70)) ``` -------------------------------- ### DrawBot: RGB Gradients and Shadows Source: https://github.com/typemytype/drawbot/blob/master/docs/content/quickReference.md Illustrates the use of RGB color space for linear and radial gradients, as well as applying shadows to shapes in DrawBot. This allows for visually rich graphic elements. ```python newPage() print("pageCount:", pageCount()) fill(1, 0, 1) linearGradient((10, 10), (200, 20), ([1, 1, 0], [0, 1, 1])) rect(10, 10, 200, 200) radialGradient((50, 410), (50, 410), ([1, 0, 1], [1, 1, 0], [0, 1, 1]), startRadius=0, endRadius=300) rect(10, 310, 100, 150) shadow((10, 10), 20, (1, 0, 0)) valentine(130, 310, 300, 150) ``` -------------------------------- ### Apply Underline to Text in Drawbot Source: https://github.com/typemytype/drawbot/blob/master/docs/content/text/textProperties.md Applies an underline style to text. Supported values are 'single', 'thick', 'double', or None. Example demonstrates setting underline, font size, and drawing text. ```python underline("single") fontSize(140) text("hello underline", (50, 50)) ``` -------------------------------- ### Get Image Resolution with imageResolution() Source: https://github.com/typemytype/drawbot/blob/master/docs/content/image/imageProperties.md Retrieves the resolution (DPI) of an image file. Compatible with PDF, JPG, PNG, TIFF, GIF, and NSImage objects. This function takes the image path as an argument. -------------------------------- ### Python Functions: Definition and Usage Source: https://github.com/typemytype/drawbot/blob/master/docs/content/courseware.md Illustrates how to define and call functions in Python, including functions with and without arguments, and functions that return values. It also touches upon variable scope (local vs. global). ```python # defining a function: def myfunction(): print("hello!") # calling the function: myfunction() # a common error # not calling the function: myfunction # note missing () # defining a function that takes an # 'argument' (or 'parameter') def mysecondfunction(x, y): print("hello!") print(x, y) # calling the function with 2 arguments mysecondfunction(123, 456) def add2numbers(x, y): # you can see 'global' vars print(aglobalvariable) result = x + y return result aglobalvariable = "hi!" thereturnedvalue = add2numbers(1, 2) print(thereturnedvalue) # 'result' was a local name inside # add2number, so it is not visible at the # top level. So the next line would cause # an error: #print(result) def anotherfunc(x, y): # calling add2numbers function: return add2numbers(x, y) print(anotherfunc(1, 2)) ``` -------------------------------- ### Create New Page with Custom Size in Python Source: https://github.com/typemytype/drawbot/blob/master/docs/content/canvas/pages.md Demonstrates creating new pages with specified dimensions and drawing content onto them. It shows how to set fill colors and draw rectangles that scale to the page size. Supported paper sizes are also listed. ```python # loop over a range of 100 for i in range(100): # for each loop create a new path newPage(500, 500) # set a random fill color fill(random(), random(), random()) # draw a rect with the size of the page rect(0, 0, width(), height()) ``` -------------------------------- ### Apply Strikethrough to Text in Drawbot Source: https://github.com/typemytype/drawbot/blob/master/docs/content/text/textProperties.md Applies a strikethrough style to text. Supported values are 'single', 'thick', 'double', or None. Example shows setting size, strikethrough, font size, and drawing text. ```python size(1000, 200) strikethrough("single") fontSize(100) text("hello strikethrough", (40, 60)) ``` -------------------------------- ### DrawBot: CMYK Colors and Gradients Source: https://github.com/typemytype/drawbot/blob/master/docs/content/quickReference.md Demonstrates how to use CMYK color modes for fills and strokes, including linear and radial gradients. It also shows how to apply CMYK shadows to shapes. ```python newPage() print("pageCount:", pageCount()) # c m y k alpha cmykFill(0, 1, 0, 0) rect(10, 10, 100, 100) strokeWidth(5) cmykFill(None) cmykStroke(0, 1, 1, 0) rect(10, 110, 100, 100) cmykLinearGradient((10, 210), (10, 310), ([1, 1, 1, 1], [0, 1, 1, 0])) rect(10, 210, 100, 100) cmykStroke(None) cmykRadialGradient((50, 410), (50, 410), ([1, 0, 1, 0], [1, 1, 0, 0], [0, 1, 1, 0]), startRadius=0, endRadius=300) rect(10, 310, 100, 150) cmykShadow((10, 10), 20, (0, 1, 1, 0)) valentine(130, 310, 300, 150) ``` -------------------------------- ### linearGradient: Generate Linear Color Gradients Source: https://github.com/typemytype/drawbot/blob/master/docs/content/image/imageObject.md Generates an image with a color gradient that transitions linearly between two specified endpoints and colors. It requires the image size, start and end points, and two RGBA colors. ```Python linearGradient(size, point0=(0.0, 0.0), point1=(200.0, 200.0), color0=(1.0, 1.0, 1.0, 1.0), color1=(0.0, 0.0, 0.0, 1.0)) ``` -------------------------------- ### Enable Hyphenation for Text in Drawbot Source: https://github.com/typemytype/drawbot/blob/master/docs/content/text/textProperties.md Controls text hyphenation, accepting a boolean value (True or False). The example demonstrates enabling hyphenation, setting font size, and drawing text within a bounding box. ```python txt = '''Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.''' # enable hyphenation hyphenation(True) # set font size fontSize(50) # draw text in a box textBox(txt, (100, 100, 800, 800)) ``` -------------------------------- ### Multi-Page Text Rendering and Animation with DrawBot Source: https://github.com/typemytype/drawbot/blob/master/docs/content/text/drawingText.md Demonstrates drawing text across multiple pages using `textBox` and a `while` loop to handle overflow. Includes animation effects by changing background colors and font sizes across frames. Saves the output as an MP4 video. Requires DrawBot's `newPage`, `frameDuration`, `fill`, `rect`, `font`, `fontSize`, `randint`, `random`, `radialGradient`, `textSize`, and `saveImage` functions. ```python t = '''DrawBot is a powerful, free application for macOS that invites you to write simple Python scripts to generate two-dimensional graphics. The builtin graphics primitives support rectangles, ovals, (bezier) paths, polygons, text objects and transparency. DrawBot is an ideal tool to teach the basics of programming. Students get colorful graphic treats while getting familiar with variables, conditional statements, functions and what have you. Results can be saved in a selection of different file formats, including as high resolution, scaleable PDF. DrawBot has proven itself as part of the curriculum at selected courses at the Royal Academy in The Hague.''' # setting some variables # setting the size x, y, w, h = 10, 10, 480, 480 # setting the color change over different frames coloradd = .1 # setting the start background color only red and blue r = .3 b = 1 # start a loop and run as long there is t variable has some text while len(t): # create a new page newPage(500, 500) # set a frame duration frameDuration(3) # set the background fill fill(r, 0, b) # draw the background rect(x, y, w, h) # set a fill color fill(0) # set a font with a size font("DrawBot-Bold", randint(50, 100)) # pick some random colors rr = random() gg = random() bb = random() # set a gradient as fill radialGradient((250, 250), (250, 250), [(rr, gg, bb), (1-rr, 1-gg, 1-bb)], startRadius=0, endRadius=250) # draw the text in a box with the gradient fill t = textBox(t, (x, y, w, h)) # setting the color for the next frame r += coloradd b -= coloradd # set a font font("DrawBot-Bold", 20) # get the page count text size as a (width, height) tuple tw, th = textSize("%s" % pageCount()) # draw the text textBox("%s" % pageCount(), (10, 10, 480, th), align="center") saveImage("~/Desktop/drawbot.mp4") ``` -------------------------------- ### Print Canvas Content Source: https://github.com/typemytype/drawbot/blob/master/docs/content/canvas/saveImage.md The `printImage` function exports the current canvas content to a printing dialog. It can optionally accept a PDF object. The example sets the page size to A4 and draws an oval before sending it to the printer. ```python # set A4 page size size(595, 842) # draw something oval(0, 0, width(), height()) # send it to the printer printImage() ```