def getProgressItems(self, curStepIndex, steps):
        total = len(steps)
        marginTop = 4
        dia = 9
        space = 12

        image = Image.new("RGB", (self.width, dia + int(marginTop * 1.5)))
        draw = Draw(image)

        w = ((dia + space) * total) - space
        marginLeft = (self.width - w) / 2

        for s in range(total):
            left = marginLeft + ((dia + space) * s)
            draw.ellipse((left, marginTop, left + dia, marginTop + dia),
                         Pen(self.colors[steps[s]]),
                         Brush(self.colors[steps[s]]))
            if curStepIndex < s:
                draw.ellipse(
                    (left + (dia * 0.25), marginTop + (dia * 0.25), left +
                     (dia * 0.75), marginTop + (dia * 0.75)), Pen("#000"),
                    Brush("#000"))
        draw.flush()

        return image
    async def loading(self):
        image = Image.new("RGB", (self.width, self.height))

        draw = Draw(image)

        colors = list(self.colors.values())
        draw.ellipse((50, 59, 60, 69), Pen(colors[0]), Brush(colors[0]))
        draw.ellipse((75, 59, 85, 69), Pen(colors[1]), Brush(colors[1]))
        draw.ellipse((100, 59, 110, 69), Pen(colors[2]), Brush(colors[2]))

        draw.flush()

        self.display(image)
Esempio n. 3
0
 def __init__(self, x, y):
     self.x = x
     self.y = y
     self.get_radius = SinFunction(phase=random.uniform(0, math.pi),
                                   amplitude=random.uniform(0.5, 1.5),
                                   del_theta=random.uniform(0.03, 0.07),
                                   mean_value=random.uniform(1.2, 3.2))
     self.status = Star.IS_HEALTHY
     self.radius = self.get_radius()
     self.color = (random.randint(0, 256), random.randint(0, 256),
                   random.randint(0, 256))
     self.brush = Brush(self.color)
     self.pen = Pen(self.color, 0)
     self.glow_brush = Brush(self.color, opacity=random.randint(20, 40))
     self.glow_offset = self.get_radius.max_value() * 1.7
     self.explode_radius = self.get_radius.max_value() * 8
Esempio n. 4
0
def drift_correct_target():
    draw_context_length = P.screen_y // 60
    while draw_context_length % 3 != 0:  # inner dot should be 1/3 size of target
        draw_context_length += 1
    black_brush = Brush((0, 0, 0, 255))
    white_brush = Brush((255, 255, 255, 255))
    draw_context = Draw("RGBA",
                        [draw_context_length + 2, draw_context_length + 2],
                        (0, 0, 0, 0))
    draw_context.ellipse([0, 0, draw_context_length, draw_context_length],
                         black_brush)
    wd_top = draw_context_length // 3  # size of the inner white dot of the calibration point
    wd_bot = 2 * draw_context_length // 3
    draw_context.ellipse([wd_top, wd_top, wd_bot, wd_bot], white_brush)

    return aggdraw_to_array(draw_context)
Esempio n. 5
0
    def draw(self):
        rotation = self.rotation
        center = self.surface_width / 2.0
        r = self.radius + 1
        for i in range(0, len(self.colors)):
            brush = Brush(rgb_to_rgba(self.colors[i]))
            vertices = [center, center]
            for i in range(0, 4):
                r_shift = -0.25 if i < 2 else 1.25
                r_shift -= rotation
                func = cos if i % 2 else sin
                vertices.append(r + r * func(radians(r_shift + 180)))
            self.surface.polygon(vertices, brush)
            rotation += 360.0 / len(self.colors)
        self.surface.flush()

        # Create annulus mask and apply it to colour disc
        mask = Image.new('L', (self.surface_width, self.surface_height), 0)
        d = Draw(mask)
        xy_1 = center - (self.radius - self.thickness / 2.0)
        xy_2 = center + (self.radius - self.thickness / 2.0)
        path_pen = Pen(255, self.thickness)
        d.ellipse([xy_1, xy_1, xy_2, xy_2], path_pen, self.transparent_brush)
        d.flush()
        self.canvas.putalpha(mask)

        return self.canvas
Esempio n. 6
0
    def initialize_renderers(self):
        '''
        We will initialize the draw objects for each individual/solution as to save computations.
        Instead of reinitializing them each iteration we will wipe the images by drawing a
        opaque rectangle in white or black. Then render the shapes on top. This method creates
        those draw objects and stores them in a list.
        '''
        self.draws = []
        self.bg_brush = Brush((0, 0, 0) if self.bg_color == 'black' else
                              (255, 255, 255), 255)
        self.bg_coords = (0, 0, *self.img_size)

        if self.shape_type in {'circle', 'square'}:
            self.render_method = self.render_uni_verts
        else:
            self.render_method = self.render_multi_verts

        if self.shape_type == 'circle':
            self.draw_method = 'ellipse'
        elif self.shape_type == 'square':
            self.draw_method = 'rectangle'
        else:
            self.draw_method = self.shape_type

        for _ in self.pop_range:
            draw = Draw('RGBA', self.img_size, self.bg_color)
            draw.setantialias(False)
            self.draws.append([draw, getattr(draw, self.draw_method)])
Esempio n. 7
0
 def draw(self):
     self.dib.rectangle((0, 0, self.winfo_width(), self.winfo_height()),
                        Pen(self.bg_color), Brush(self.bg_color))
     self.galaxy.draw(self.dib)
     self.death_circle.draw(self.dib)
     self.time_ring.draw(self.dib)
     self.dib.expose(hwnd=self.winfo_id())
     self.death_circle.update()
Esempio n. 8
0
 def fill(self, color):
     if not color:
         self.fill_color = None
         return self
     color = list(color)
     if len(color) == 3:
         color += [255]
     self.fill_color = color
     self.__fill = Brush(tuple(color[:3]), color[3])
     if self.surface:  # don't call this when initializing the Drawbject for the first time
         self._init_surface()
     return self
Esempio n. 9
0
 def addCanvasPolygon(self, ps, color=(0, 0, 0), fill=True, stroke=False, **kwargs):
   if not fill and not stroke:
     return 
   dps = []
   for p in ps:
     dps.extend(p)
   color = convertColor(color)
   brush = None
   pen = None
   if fill:
     brush = Brush(color)
   if stroke:
     pen = Pen(color)
   self.draw.polygon(dps, pen, brush)
Esempio n. 10
0
def _fill_annotations(a: Annotation, label: str, color=0xFF, out=None):
    if out is None:
        out = Image.new(mode='L', size=a.image.size)

    brush = Brush(color)

    d = Draw(out)
    d.setantialias(False)

    for o in a.iter_objects(label):
        xy = a.points(o)
        d.polygon(xy.flatten(), brush)

    return d.flush()
Esempio n. 11
0
def test_brush():
    from aggdraw import Brush
    Brush("black")
    Brush("black", opacity=128)

    Brush(0)
    Brush((0, 0, 0))
    Brush("rgb(0, 0, 0)")
    Brush("gold")
Esempio n. 12
0
def make_marker(radius, fill_color, stroke_color, stroke_width, opacity=1.0):
    """
    Creates a map marker and returns a PIL image.

    radius
        In pixels

    fill_color
        Any PIL-acceptable color representation, but standard hex
        string is best

    stroke_color
        See fill_color

    stroke_width
        In pixels

    opacity
        Float between 0.0 and 1.0
    """
    # Double all dimensions for drawing. We'll resize back to the original
    # radius for final output -- it makes for a higher-quality image, especially
    # around the edges
    radius, stroke_width = radius * 2, stroke_width * 2
    diameter = radius * 2
    im = Image.new('RGBA', (diameter, diameter))
    draw = Draw(im)
    # Move in from edges half the stroke width, so that the stroke is not
    # clipped.
    half_stroke_w = (stroke_width / 2 * 1.0) + 1
    min_x, min_y = half_stroke_w, half_stroke_w
    max_x = diameter - half_stroke_w
    max_y = max_x
    bbox = (min_x, min_y, max_x, max_y)
    # Translate opacity into aggdraw's reference (0-255)
    opacity = int(opacity * 255)
    draw.ellipse(bbox,
                 Pen(stroke_color, stroke_width, opacity),
                 Brush(fill_color, opacity))
    draw.flush()
    # The key here is to resize using the ANTIALIAS filter, which is very
    # high-quality
    im = im.resize((diameter / 2, diameter / 2), Image.ANTIALIAS)
    return im
Esempio n. 13
0
def cursor(color=None):
    dc = Draw("RGBA", [32, 32], (0, 0, 0, 0))
    if color is not None:
        cursor_color = color[0:3]
    else:
        cursor_color = []
        for c in P.default_fill_color:
            cursor_color.append(abs(c - 255))
        cursor_color = cursor_color[0:3]
    # coordinate tuples are easier to read/modify but aggdraw needs a stupid x,y,x,y,x,y list
    cursor_coords = [(6, 0), (6, 27), (12, 21), (18, 32), (20, 30), (15, 20),
                     (23, 20), (6, 0)]
    cursor_xy_list = []
    for point in cursor_coords:
        cursor_xy_list.append(point[0])
        cursor_xy_list.append(point[1])
    brush = Brush(tuple(cursor_color), 255)
    pen = Pen((255, 255, 255), 1, 255)
    dc.polygon(cursor_xy_list, pen, brush)
    cursor_surface = aggdraw_to_array(dc)
    return cursor_surface
Esempio n. 14
0
def test_graphics():
    from aggdraw import Draw, Pen, Brush
    draw = Draw("RGB", (500, 500))

    pen = Pen("black")
    brush = Brush("black")

    draw.line((50, 50, 100, 100), pen)

    draw.rectangle((50, 150, 100, 200), pen)
    draw.rectangle((50, 220, 100, 270), brush)
    draw.rectangle((50, 290, 100, 340), brush, pen)
    draw.rectangle((50, 360, 100, 410), pen, brush)

    draw.ellipse((120, 150, 170, 200), pen)
    draw.ellipse((120, 220, 170, 270), brush)
    draw.ellipse((120, 290, 170, 340), brush, pen)
    draw.ellipse((120, 360, 170, 410), pen, brush)

    draw.polygon((190+25, 150, 190, 200, 190+50, 200), pen)
    draw.polygon((190+25, 220, 190, 270, 190+50, 270), brush)
    draw.polygon((190+25, 290, 190, 340, 190+50, 340), brush, pen)
    draw.polygon((190+25, 360, 190, 410, 190+50, 410), pen, brush)
Esempio n. 15
0
 def round_corner_jpg(image, radius):
     """Round a JPG image"""
     mask = Image.new('L', image.size)
     draw = Draw(mask)
     brush = Brush('white')
     width, height = mask.size
     draw.pieslice((0, 0, radius * 2, radius * 2), 90, 180, None, brush)
     draw.pieslice((width - radius * 2, 0, width, radius * 2), 0, 90, None,
                   brush)
     draw.pieslice((0, height - radius * 2, radius * 2, height), 180, 270,
                   None, brush)
     draw.pieslice((width - radius * 2, height - radius * 2, width, height),
                   270, 360, None, brush)
     draw.rectangle((radius, radius, width - radius, height - radius),
                    brush)
     draw.rectangle((radius, 0, width - radius, radius), brush)
     draw.rectangle((0, radius, radius, height - radius), brush)
     draw.rectangle((radius, height - radius, width - radius, height),
                    brush)
     draw.rectangle((width - radius, radius, width, height - radius), brush)
     draw.flush()
     image = image.convert('RGBA')
     image.putalpha(mask)
     return image
Esempio n. 16
0
    def start(self, tag: str, attrib):
        (ns, tag) = self.get_ns_tag(tag)
        if ns != self.svgns:
            return

        if self.draw and self.text != "":
            self.flush_text()

        self.tagstack.append((tag, attrib))

        if self.draw:
            self.apply_style(tag, attrib)

        if not self.draw and not tag == "svg":
            return

        if tag == "svg":
            self.svgsize = (float(
                self.get_attribute("width", self.imagesize[0], False)),
                            float(
                                self.get_attribute("height", self.imagesize[1],
                                                   False)))
            if ("viewBox" in attrib):
                self.svgviewbox = list(
                    map(lambda s: float(s.strip()),
                        filter(None, attrib["viewBox"].split(" "))))
            else:
                self.svgviewbox = [0, 0, self.svgsize[0], self.svgsize[1]]
            #print self.svgViewBox

        if tag == "style":
            self.parse_style_tag()

        elif tag == "rect":
            #print self.tagStack[-1][1]
            (x1, y1) = self.get_coords(attrib["x"], attrib["y"])
            (x2, y2) = self.get_coords(
                float(attrib["x"]) + float(attrib["width"]),
                float(attrib["y"]))
            (x3, y3) = self.get_coords(
                float(attrib["x"]) + float(attrib["width"]),
                float(attrib["y"]) + float(attrib["height"]))
            (x4, y4) = self.get_coords(
                float(attrib["x"]),
                float(attrib["y"]) + float(attrib["height"]))

            if not isinstance(self.draw, ImageDraw.ImageDraw):
                from aggdraw import Brush, Pen, Draw
                draw = cast(Draw, self.draw)
                draw.setantialias(False)
                self.draw.polygon([x1, y1, x2, y2, x3, y3, x4, y4],
                                  Brush('black'))
                # self.draw.polygon([20, 20, 21, 20, 21, 21, 20, 21], Brush('green'))
                # self.draw.polygon([20, 0, 21, 0, 21, 1, 20, 1], Brush('blue'))
                # self.draw.polygon([22, 0, 22, 1, 23, 1, 23, 0], Brush('red'))
                draw.flush()
            else:
                self.draw.polygon(
                    [x1, y1, x2, y2, x3, y3, x4, y4],
                    outline=self.parse_color(
                        self.get_attribute("stroke", "none", True),
                        float(self.get_attribute("stroke-opacity", "1",
                                                 False))),
                    fill=self.parse_color(
                        self.get_attribute("fill", "none", True),
                        float(self.get_attribute("fill-opacity", "1", False))))
                # self.draw.polygon([20, 20, 21, 20, 21, 21, 20, 21], fill='green')
                # self.draw.polygon([20, 0, 21, 0, 21, 1, 20, 1], fill='blue')
                # self.draw.polygon([22, 0, 22, 0, 22, 1, 22, 1], fill='red')

        elif tag == "ellipse" or tag == "circle":
            cc = 0.55191502449
            cx = float(attrib["cx"])
            cy = float(attrib["cy"])
            if tag == "ellipse":
                rx = float(attrib["rx"])
                ry = float(attrib["ry"])
            else:
                rx = float(attrib["r"])
                ry = float(attrib["r"])

            w = rx
            h = ry

            self.draw_path([
                "M", cx - w, cy, "C", cx - w, cy - cc * h, cx - cc * w, cy - h,
                cx, cy - h, "S", cx + w, cy - cc * h, cx + w, cy, "S",
                cx + cc * w, cy + h, cx, cy + h, "S", cx - w, cy + cc * h,
                cx - w, cy, "z"
            ])

        elif tag == "polyline":
            path_data = self.parse_path_data(
                self.get_attribute("points", "", False))
            self.draw_path(path_data)

        elif tag == "path":
            path_data = self.parse_path_data(self.get_attribute(
                "d", "", False))
            self.draw_path(path_data)

        elif tag == "text" or tag == "tspan":
            if "x" in attrib:
                self.lasttextpoint = self.get_coords(
                    self.get_attribute("x", 0, True),
                    self.get_attribute("y", 0, True))

        self.depth += 1
Esempio n. 17
0
 def render_multi_verts(self, draw_method, shape):
     '''
     For rendering shapes that have multiple vertices: rectangles and polygons
     '''
     draw_method(shape[:self.n_xy],
                 Brush(tuple(shape[self.n_xy:-1]), shape[-1]))
Esempio n. 18
0
 def render_uni_verts(self, draw_method, shape):
     '''
     For rendering shapes that have a single vertex and a radius such as circles and squares
     '''
     draw_method((*shape[:self.n_xy], shape[1] + shape[2] - shape[0]),
                 Brush(tuple(shape[self.n_xy:-1]), shape[-1]))
Esempio n. 19
0
    def addCanvasText(self, text, pos, font, color=(0, 0, 0), **kwargs):
        orientation = kwargs.get('orientation', 'E')
        color = convertColor(color)
        aggFont = Font(color,
                       faceMap[font.face],
                       size=font.size * self.fontScale)

        blocks = list(re.finditer(r'\<(.+?)\>(.+?)\</\1\>', text))
        w, h = 0, 0
        supH = 0
        subH = 0
        if not len(blocks):
            w, h = self.draw.textsize(text, aggFont)
            bw, bh = w * 1.1, h * 1.1
            dPos = pos[0] - bw / 2., pos[1] - bh / 2.
            bgColor = kwargs.get('bgColor', (1, 1, 1))
            bgColor = convertColor(bgColor)
            self.draw.rectangle((dPos[0], dPos[1], dPos[0] + bw, dPos[1] + bh),
                                None, Brush(bgColor))
            dPos = pos[0] - w / 2., pos[1] - h / 2.
            self.draw.text(dPos, text, aggFont)
        else:
            dblocks = []
            idx = 0
            for block in blocks:
                blockStart, blockEnd = block.span(0)
                if blockStart != idx:
                    # untagged text:
                    tblock = text[idx:blockStart]
                    tw, th = self.draw.textsize(tblock, aggFont)
                    w += tw
                    h = max(h, th)
                    dblocks.append((tblock, '', tw, th))
                fmt = block.groups()[0]
                tblock = block.groups()[1]
                if fmt in ('sub', 'sup'):
                    lFont = Font(color,
                                 faceMap[font.face],
                                 size=0.8 * font.size * self.fontScale)
                else:
                    lFont = aggFont
                tw, th = self.draw.textsize(tblock, lFont)
                w += tw
                if fmt == 'sub':
                    subH = max(subH, th)
                elif fmt == 'sup':
                    supH = max(supH, th)
                else:
                    h = max(h, th)
                dblocks.append((tblock, fmt, tw, th))
                idx = blockEnd
            if idx != len(text):
                # untagged text:
                tblock = text[idx:]
                tw, th = self.draw.textsize(tblock, aggFont)
                w += tw
                h = max(h, th)
                dblocks.append((tblock, '', tw, th))

            supH *= 0.25
            subH *= 0.25
            h += supH + subH
            bw, bh = w * 1.1, h
            #dPos = pos[0]-bw/2.,pos[1]-bh/2.
            dPos = [pos[0] - w / 2., pos[1] - h / 2.]
            if orientation == 'W':
                dPos = [pos[0] - w, pos[1] - h / 2.]
            elif orientation == 'E':
                dPos = [pos[0], pos[1] - h / 2.]
            else:
                dPos = [pos[0] - w / 2, pos[1] - h / 2.]

            bgColor = kwargs.get('bgColor', (1, 1, 1))
            bgColor = convertColor(bgColor)
            self.draw.rectangle((dPos[0], dPos[1], dPos[0] + bw, dPos[1] + bh),
                                None, Brush(bgColor))
            if supH: dPos[1] += supH
            for txt, fmt, tw, th in dblocks:
                tPos = dPos[:]
                if fmt == 'sub':
                    tPos[1] += subH
                elif fmt == 'sup':
                    tPos[1] -= supH
                if fmt in ('sub', 'sup'):
                    lFont = Font(color,
                                 faceMap[font.face],
                                 size=0.8 * font.size * self.fontScale)
                else:
                    lFont = aggFont
                self.draw.text(tPos, txt, lFont)
                dPos[0] += tw
Esempio n. 20
0
class Drawbject(object):
    """An abstract class that serves as the foundation for all KLDraw shapes. All Drawbjects
	are drawn on an internal surface using the aggdraw drawing library, which can then be drawn
	to the display buffer using blit() and displayed on the screen using flip(). For more
	infomration on drawing in KLibs, please refer to the guide in the documentation.

	Args:
		width (int): The width of the shape in pixels.
		height (int): The height of the shape in pixels.
		stroke (List[width, Tuple[color], alignment]): The stroke of the shape, indicating
			the width, color, and alignment (inner, center, or outer) of the stroke.
		fill (Tuple[color]): The fill color for the shape expressed as an iterable of integer 
			values from 0 to 255 representing an RGB or RGBA color (e.g. (255,0,0,128)
			for bright red with 50% transparency.)
		rotation (int|float, optional): The degrees by which to rotate the Drawbject during
			rendering. Defaults to 0.

	Attributes:
		stroke_color (None or Tuple[color]): The stroke color for the shape, expressed as an
			iterable of integer values from 0 to 255 representing an RGB or RGBA color.
			Defaults to 'None' if the shape has no stroke.
		stroke_width (int): The stroke width for the in pixels. Defaults to '0' if the
			shape has no stroke.
		stroke_alignment (int): The stroke alignment for the shape (inner, center, or
			outer). Defaults to '1' (STROKE_INNER) if the shape has no stroke.
		fill_color (None or Tuple[color]): The fill color for the shape, expressed as an
			iterable of integer values from 0 to 255 representing an RGB or RGBA color.
			Defaults to 'None' if the shape has no fill.
		opacity (int): The opacity of the shape, expressed as an integer from 0 (fully
			transparent) to 255 (fully opaque).
		object_width (int): The width of the shape in pixels.
		object_height (int): The height of the shape in pixels.
		surface_width (int): The width of the draw surface in pixels. At minimum two 
			pixels wider than the object_width (if no stroke or stroke is inner aligned),
			at maximum (2 + 2*stroke_width) pixels wider than object width (if stroke is
			outer aligned).
		surface_height (int): The height of the draw surface in pixels. At minimum two 
			pixels wider than the object_height (if no stroke or stroke is inner aligned),
			at maximum (2 + 2*stroke_height) pixels wider than object height (if stroke is
			outer aligned).
		surface (:obj:`aggdraw.Draw`): The aggdraw context on which the shape is drawn.
			When a shape is drawn to the surface, it is immediately applied to the canvas.
		canvas (:obj:`PIL.Image.Image`): The Image object that contains the shape of the
			Drawbject before opacity has been applied. Initialized upon creation with a
			size of (surface_width x surface_height).
		rendered (None or :obj:`numpy.array`): The rendered surface containing the shape,
			which is created using the render() method. If the Drawbject has not yet been
			rendered, this attribute will be 'None'.
		rotation (int): The rotation of the shape in degrees. Will be equal to 0 if no
			rotation is set.

	"""

    transparent_brush = Brush((255, 0, 0), 0)

    def __init__(self, width, height, stroke, fill, rotation=0):
        super(Drawbject, self).__init__()

        self.surface = None
        self.canvas = None
        self.rendered = None

        self.__stroke = None
        self.stroke_width = 0
        self.stroke_color = None
        self.stroke_alignment = STROKE_OUTER
        self.stroke = stroke

        self.__fill = None
        self.fill_color = None
        self.fill = fill

        self.__dimensions = None
        self.object_width = width
        self.object_height = height
        self.rotation = rotation

        self._init_surface()

    def __str__(self):
        properties = [
            self.__name__, self.surface_width, self.surface_height,
            hex(id(self))
        ]
        return "klibs.Drawbject.{0} ({1} x {2}) at {3}".format(*properties)

    def _init_surface(self):
        self._update_dimensions()
        self.rendered = None  # Clear any existing rendered texture
        if self.fill_color:
            if self.stroke_color and self.fill_color[3] == 255:
                col = self.stroke_color
            else:
                col = self.fill_color
        elif self.stroke_color:
            col = self.stroke_color
        else:
            col = (0, 0, 0)
        self.canvas = Image.new("RGBA", self.dimensions,
                                (col[0], col[1], col[2], 0))
        self.surface = Draw(self.canvas)
        self.surface.setantialias(True)

    def render(self):
        """Pre-renders the shape so it can be drawn to the screen using
		:func:`~klibs.KLGraphics.blit`. Although it is not necessary to pre-render
		shapes before drawing them to the screen, it will make the initial blit faster
		and is recommended wherever possible. 
		
		Once a Drawbject has been rendered, it will not need to be rendered again unless
		any of its properties (e.g. stroke, fill, rotation) are changed.
		
		Returns:
			:obj:`~numpy.ndarray`: A numpy array of the rendered shape.

		"""
        self._init_surface()
        self.draw()
        self.rendered = asarray(self.canvas)
        return self.rendered

    def _update_dimensions(self):
        pts = self._draw_points(outline=True)
        if pts != None:
            self.__dimensions = canvas_size_from_points(pts, flat=True)
        else:
            if self.stroke_alignment == STROKE_OUTER:
                stroke_w = self.stroke_width * 2
            elif self.stroke_alignment == STROKE_CENTER:
                stroke_w = self.stroke_width
            else:
                stroke_w = 0
            w, h = [self.object_width, self.object_height]
            self.__dimensions = [
                int(ceil(w + stroke_w)) + 2,
                int(ceil(h + stroke_w)) + 2
            ]

    @property
    def dimensions(self):
        """List[int, int]: The height and width of the internal surface on which the shape
		is drawn.
		"""
        return self.__dimensions

    @property
    def surface_width(self):
        return self.__dimensions[0]

    @property
    def surface_height(self):
        return self.__dimensions[1]

    @property
    def stroke(self):
        """None or :obj:`aggdraw.Pen`: An aggdraw Pen object set to the specified stroke width
		and color, or None if the Drawbject has no stroke.

		Raises:
			ValueError: If an invalid stroke alignment value is passed to the stroke setter.
				Valid values are 1 (STROKE_INNER), 2 (STROKE_CENTER), or 3 (STROKE_OUTER).
				For the sake of clarity, it is recommended that you define stroke alignment
				using the variable names provided in KLConstants (in brackets above).

		"""
        return self.__stroke

    @stroke.setter
    def stroke(self, style):
        if not style:
            self.stroke_width = 0
            self.stroke_color = None
            self.stroke_alignment = STROKE_OUTER
            return self
        try:
            width, color, alignment = style
        except ValueError:
            width, color = style
            alignment = STROKE_OUTER

        if alignment in [STROKE_INNER, STROKE_CENTER, STROKE_OUTER]:
            self.stroke_alignment = alignment
        else:
            raise ValueError(
                "Invalid stroke alignment, see KLConstants for accepted values"
            )

        color = list(color)
        if len(color) == 3:
            color += [255]
        self.stroke_color = color
        self.stroke_width = width
        self.__stroke = Pen(tuple(color[:3]), width, color[3])
        if self.surface:  # don't call this when initializing the Drawbject for the first time
            self._init_surface()
        return self

    @property
    def stroke_offset(self):
        if self.stroke_alignment == STROKE_OUTER:
            return self.stroke_width * 0.5
        if self.stroke_alignment == STROKE_INNER:
            return self.stroke_width * -0.5
        else:
            return 0

    @property
    def fill(self):
        """None or :obj:`aggdraw.Brush`: An aggdraw Brush object set to the specified fill
		color, or None if the Drawbject has no fill.
		
		"""
        return self.__fill

    @fill.setter
    def fill(self, color):
        if not color:
            self.fill_color = None
            return self
        color = list(color)
        if len(color) == 3:
            color += [255]
        self.fill_color = color
        self.__fill = Brush(tuple(color[:3]), color[3])
        if self.surface:  # don't call this when initializing the Drawbject for the first time
            self._init_surface()
        return self

    @abc.abstractmethod
    def _draw_points(self, outline=False):
        return None

    @abc.abstractmethod
    def draw(self):
        pts = self._draw_points()
        dx = self.surface_width / 2.0
        dy = self.surface_height / 2.0
        pts = translate_points(pts, delta=(dx, dy), flat=True)

        self.surface.polygon(pts, self.stroke, self.fill)
        self.surface.flush()
        return self.canvas

    @abc.abstractproperty
    def __name__(self):
        pass
Esempio n. 21
0
 def __init__(self):
     self.__is_growing = False
     self.__radius = 0
     self.__center = (0, 0)
     self.__pen = Pen("red", 0)
     self.__brush = Brush("red", 50)
Esempio n. 22
0
from PIL import Image
from aggdraw import Draw, Brush
transBlack = (0, 0, 0, 0)  # shows your example with visible edges
solidBlack = (0, 0, 0, 255)  # shows shape on a black background
transWhite = (255, 255, 255, 0)
solidWhite = (255, 255, 255, 255)

im = Image.new("RGBA", (600, 600), solidBlack)

draw = Draw(im)

brush = Brush("yellow")

draw.polygon((
    50,
    50,
    550,
    60,
    550,
    550,
    60,
    550,
), None, brush)

draw.flush()
im.save("squar.png")
im.show()
Esempio n. 23
0
 def draw(self, draw_obj):
     brush = Brush(self.color)
     draw_obj.ellipse(
         (self.center_x - self.radius_x, self.center_y - self.radius_y,
          self.center_x + self.radius_x, self.center_y + self.radius_y),
         brush)