BOXES v0.1

Welcome to Boxes v1. I want to be able to draw some boxes. By boxes I don't mean actual boxes, but rather squares. I found a library called svgwrite that lets you do that pretty easily.

First let's create a data structure. A simple class called Box.

 1class Box():
 2
 3    def __init__(self, x=0, y=0, w=1, h=1):
 4        """Accept arguments to define our box, and store them."""
 5        self.x = x
 6        self.y = y
 7        self.w = w
 8        self.h = h
 9
10    def __repr__(self):
11        return "Box(%s, %s, %s, %s)" % (self.x, self.y, self.w, self.h)

As you can see that is a pretty simple class. And we can create a big box.

big_box = Box(0, 0, 80, 100)

Or many boxes using a list comprehension

14many_boxes = [Box() for i in range(5000)]

So now we have a big box, and 5000 smaller boxes, all alike.

1# Print the first 10 boxes
2print(many_boxes[:10])
[Box(0, 0, 1, 1), Box(0, 0, 1, 1), Box(0, 0, 1, 1), Box(0, 0, 1, 1), Box(0, 0, 1, 1), Box(0, 0, 1, 1), Box(0, 0, 1, 1), Box(0, 0, 1, 1), Box(0, 0, 1, 1), Box(0, 0, 1, 1)]

And yes, we can draw those boxes. Because this is python 3.6 or higher I am using f-strings. All the cm you see there are because we are creating SVG images and they have physical sizes, so I am doing everything in centimeters (yay metric system), to avoid using things like the default unit, which is points (1/72 of an inch) or some other similar nonsense.

16import svgwrite
17
18
19def draw_boxes(boxes, fname, size):
20    dwg = svgwrite.Drawing(fname, profile="full", size=size)
21    # Draw all the boxes
22    for box in boxes:
23        dwg.add(
24            dwg.rect(
25                insert=(f"{box.x}cm", f"{box.y}cm"),
26                size=(f"{box.w}cm", f"{box.h}cm"),
27                fill="red",
28            )
29        )
30    dwg.save()
31
32
33draw_boxes(many_boxes, "lesson1.svg", ("5cm", "2cm"))

And here is the output:

lesson1.svg

That ... was not very interesting. It's a single small red square! Where are all the remaining 4999 boxes?

Remember, all our boxes have the same size and position!

So ... we should do something better. Or at least more interesting, in lesson 2.


Further references:

results matching ""

    No results matching ""