Beispiel #1
0
def convert_svg2png(infile, outfile, w, h):
    """
        Converts svg files to png using Cairosvg or Inkscape
        @file_path : String; the svg file absolute path
        @dest_path : String; the png file absolute path
    """
    if use_inkscape:
        cmd = Popen(["inkscape", "-z", "-f", infile, "-e", outfile,
                     "-w", str(w), "-h", str(h)],
                    stdout=PIPE, stderr=PIPE)
        cmd.communicate()
    else:
        handle = Rsvg.Handle()
        svg = handle.new_from_file(infile)
        dim = svg.get_dimensions()

        img = ImageSurface(FORMAT_ARGB32, w, h)
        ctx = Context(img)
        ctx.scale(w / dim.width, h / dim.height)
        svg.render_cairo(ctx)

        png_io = BytesIO()
        img.write_to_png(png_io)
        with open(outfile, 'wb') as fout:
            fout.write(png_io.getvalue())
        svg.close()
        png_io.close()
        img.finish()
Beispiel #2
0
    def _onExpose(self, widget, event):
        svgh = rsvg.Handle()
        try:
            svgh.write(bytes(self.svg, "utf-8"))
        except (GObject.GError, KeyError, ValueError) as ex:
            print('Error reading SVG for display: %s\r\n%s', ex, self.svg)
            svgh.close()
            return
        svgh.close()

        if not self._composited:
            # Draw the screengrab of the underlaying window, and set the drawing
            # operator to OVER.
            self.window.draw_image(self.style.black_gc, self.root,
                                   event.area.x, event.area.y, event.area.x,
                                   event.area.y, event.area.width,
                                   event.area.height)
            cairo_operator = cairo.OPERATOR_OVER
        else:
            cairo_operator = cairo.OPERATOR_SOURCE
        window = self.get_window()
        cr = window.cairo_create()
        cr.set_source_rgba(1.0, 1.0, 1.0, 0.0)
        cr.set_operator(cairo_operator)
        cr.paint()

        svgh.render_cairo(cr)
        del svgh
Beispiel #3
0
    def snapshot(self,
                 snapshot: Gtk.Snapshot,
                 bounds: Graphene.Rect,
                 fgcolor: Gdk.RGBA, scale: float):
        # Drawing cached textures is in large scale faster than rendering
        # the svg over and over
        if self._cached_texture_scale < scale:
            scaled_w = int(WIDTH * scale)
            scaled_h = int(HEIGHT * scale)

            cr = cairo.ImageSurface(
                cairo.Format.ARGB32, scaled_w, scaled_h)
            ctx = cairo.Context(cr)
            rect = Rsvg.Rectangle()
            rect.x = 0
            rect.y = 0
            rect.width = scaled_w
            rect.height = scaled_h
            self._handle.render_document(ctx, rect)

            pixbuf = Gdk.pixbuf_get_from_surface(cr, 0, 0, scaled_w, scaled_h)
            self._cached_texture = Gdk.Texture.new_for_pixbuf(pixbuf)
            self._cached_texture_scale = scale

        snapshot.append_texture(self._cached_texture, bounds)
Beispiel #4
0
    def __init__(self, music_info):
        self.music_info = music_info
        self.border_gap = 10.
        width, height = 300, 7 * 4 * 5
        self.size = layout.datatypes.Point(width + self.border_gap * 2, height + self.border_gap * 2)

        self.symbols_svg = Rsvg.Handle().new_from_file(os.path.join("artwork", "music_symbols.svg"))
Beispiel #5
0
def render_icons(source_directory, output_directory, scale):

    targets = []
    # Verify svg files exist
    for file in os.listdir(source_directory):
        if file.endswith(".svg") and os.path.isfile(
                os.path.join(source_directory, file)):
            targets.append(file)

    if not os.path.exists(output_directory):
        os.makedirs(output_directory)

    # Render svg files to png
    for file in targets:
        name = os.path.splitext(file)[0]
        in_path = os.path.join(source_directory, file)
        out_path = os.path.join(output_directory, name + ".png")

        handle = Rsvg.Handle()
        svg = handle.new_from_file(in_path)

        unscaled_width = svg.props.width
        unscaled_height = svg.props.height

        width = unscaled_width * scale
        height = unscaled_height * scale

        svg_surface = cairo.SVGSurface(None, width, height)
        svg_context = cairo.Context(svg_surface)
        svg_context.save()
        svg_context.scale(width / unscaled_width, height / unscaled_height)
        svg.render_cairo(svg_context)
        svg_context.restore()

        svg_surface.write_to_png(out_path)
    def _get_svg(ctx, path, height):
        """
        Read SVG file and rescale it to fit within height.

        Args:
           ctx (cairo.Context): The cairo context to use to draw.
           path (string): the SVG file path.
           height (number): final height of the SVG (cairo units).

        Return a tuple (cairo group object for the SVG, SVG width in
                        cairo units).
        """
        handle = Rsvg.Handle()
        try:
            svg = handle.new_from_file(path)
        except Exception:
            LOG.warning("Cannot read SVG from '%s'." % path)
            return None, None

        scale_factor = height / svg.props.height

        ctx.push_group()
        ctx.save()
        ctx.move_to(0, 0)
        factor = height / svg.props.height
        ctx.scale(factor, factor)
        svg.render_cairo(ctx)
        ctx.restore()
        return ctx.pop_group(), svg.props.width * factor
def draw_road_marking(ctx, marking):
    marking_visual = ROADMARKING_TYPE_TO_VISUAL[marking.type]
    if marking_visual.marker_text:
        ctx.save()
        ctx.set_dash([])
        font = "DIN 1451 Std"
        font_size = 0.4
        text = '30'
        font_args = [cairo.FONT_SLANT_NORMAL]
        ctx.translate(
            marking.centerPoint.x,  #- 0.145*math.cos(marking.orientation),
            marking.centerPoint.y)  #- 0.145*math.sin(marking.orientation))
        ctx.rotate(marking.orientation)
        # mirror text
        ctx.transform(cairo.Matrix(1.0, 0, 0, -1, 0, 0))
        ctx.translate(-0.145, 0.29)
        ctx.select_font_face(font, *font_args)
        ctx.set_font_size(font_size)
        ctx.text_path(marking_visual.marker_text)
        ctx.set_line_width(0.01)
        (x_bearing, y_bearing, text_width, text_height, x_advance,
         y_advance) = ctx.text_extents(text)
        ctx.fill_preserve()
        ctx.stroke()
        ctx.restore()
    if marking_visual.crossed:
        ctx.save()
        ctx.move_to(
            marking.centerPoint.x + 0.145 * math.cos(marking.orientation),
            marking.centerPoint.y + 0.145 * math.sin(marking.orientation))
        ctx.line_to(
            marking.centerPoint.x + 0.145 * math.cos(marking.orientation) -
            text_height * math.cos(marking.orientation) +
            text_width * math.sin(marking.orientation),
            marking.centerPoint.y + 0.145 * math.sin(marking.orientation) -
            text_height * math.sin(marking.orientation) -
            text_width * math.cos(marking.orientation))
        ctx.move_to(
            marking.centerPoint.x +
            (0.145 - text_height) * math.cos(marking.orientation),
            marking.centerPoint.y +
            (0.145 - text_height) * math.sin(marking.orientation))
        ctx.line_to(
            marking.centerPoint.x + 0.145 * math.cos(marking.orientation) +
            text_width * math.sin(marking.orientation),
            marking.centerPoint.y + 0.145 * math.sin(marking.orientation) -
            text_width * math.cos(marking.orientation))
        ctx.set_line_width(0.05)
        ctx.stroke()
        ctx.restore()

    if marking_visual.marker_image:
        ctx.save()
        handle = Rsvg.Handle()
        svg = handle.new_from_file(marking_visual.marker_image.value)
        ctx.translate(marking.centerPoint.x, marking.centerPoint.y)
        ctx.rotate(marking.orientation)
        ctx.scale(0.001, 0.001)
        svg.render_cairo(ctx)
        ctx.restore()
Beispiel #8
0
 def __init__(self, filename):
     if os.stat(filename).st_size == 0:
         self._svg = None
         return
     handle = Rsvg.Handle()
     self._svg = handle.new_from_file(filename)
     self._image = None
Beispiel #9
0
    def __init__(self):
        super().__init__()
        self.button = Mx.Button()

        self.script = Clutter.Script()
        self.script.load_from_file('concept/mxButton/button.json')

        self.button = self.script.get_object('button')

        self.icon = self.script.get_object('icon')

        handle = Rsvg.Handle()
        svg = handle.new_from_file('concept/mxButton/edytuj.svg')

        pixbuf = svg.get_pixbuf()

        pixbuf = pixbuf.scale_simple(100, 100, 3)

        self.icon.set_from_data(pixbuf.get_pixels(),
                                Cogl.PixelFormat.RGBA_8888, pixbuf.get_width(),
                                pixbuf.get_height(), pixbuf.get_rowstride())

        self.add_child(self.button)
        self.layout = Clutter.BinLayout()
        self.set_layout_manager(self.layout)
Beispiel #10
0
    def __init__(self, halcomp, builder, useropts):
        self.halcomp = halcomp
        self.builder = builder
        self.ini_filename = 'savestate.sav'
        self.defaults = {
            IniFile.vars:
            dict(),
            IniFile.widgets:
            widget_defaults(
                select_widgets(self.builder.get_objects(),
                               hal_only=False,
                               output_only=True))
        }
        self.ini = IniFile(self.ini_filename, self.defaults, self.builder)
        self.ini.restore_state(self)

        # A pin to use a physical switch to start the cycle
        self.cycle_start = hal_glib.GPin(
            halcomp.newpin('cycle-start', hal.HAL_BIT, hal.HAL_IN))
        self.cycle_start.connect('value-changed', self.cycle_pin)

        # This catches the signal from Touchy to say that the tab is exposed
        t = self.builder.get_object('eventbox1')
        t.connect('map-event', self.on_map_event)
        t.add_events(Gdk.EventMask.STRUCTURE_MASK)
        self.cmd = linuxcnc.command()

        # This connects the expose event to re-draw and scale the SVG frames
        t = self.builder.get_object('tabs1')
        t.connect_after("draw", self.on_expose)
        t.connect("destroy", Gtk.main_quit)
        t.add_events(Gdk.EventMask.STRUCTURE_MASK)
        self.svg = Rsvg.Handle().new_from_file('LatheMacro.svg')
        self.active = True
Beispiel #11
0
def svg_dimensions(svg, dpi=90.0):
    """
    extract svg dimensions using rsvg library

    See librsvg documentation
        https://wiki.gnome.org/action/show/Projects/LibRsvg
        https://developer.gnome.org/rsvg/stable/
        https://lazka.github.io/pgi-docs/Rsvg-2.0/classes/Handle.html

    Arguments:
        svg(string|bytes): String containig svg file
        dpi(float): dpi used for unit conversion to px

    Returns:
        (int, int): svg width and height in px
    """
    try:
        handle = Rsvg.Handle()
        if isinstance(svg, str):
            svg = svg.encode('utf8')
        svg = handle.new_from_data(svg)
        svg.set_dpi(float(dpi))
        dim = svg.get_dimensions()
        return dim.width, dim.height
    except Exception:
        raise ValueError(DIMENSIONS_ERROR_MSG)
Beispiel #12
0
def _show_symbol(renderer, ctx, lat, lon, surveillance, symbol):
    if surveillance != 'public' and surveillance != 'outdoor' and surveillance != 'indoor':
        surveillance = 'public'

    symbol_path = os.path.abspath(
        os.path.join(os.path.dirname(__file__), 'images', surveillance,
                     (symbol + '.svg')))

    fp = open(symbol_path, 'rb')
    data = fp.read()
    fp.close()

    rsvg = Rsvg.Handle()
    svg = rsvg.new_from_data(data)
    x, y = renderer._latlon2xy(lat, lon, renderer.dpi)

    svg_scale = renderer.dpi / (4 * svg.props.height)
    sx = x - svg.props.width * svg_scale / 2
    sy = y - svg.props.height * svg_scale / 2

    ctx.save()
    ctx.translate(sx, sy)
    ctx.scale(svg_scale, svg_scale)
    svg.render_cairo(ctx)
    ctx.restore()
Beispiel #13
0
    def convert_to_png(input_file, output_file, width=None, height=None):
        """Convert svg to png."""
        if width and height:
            handle = Rsvg.Handle()
            svg = handle.new_from_file(input_file)
            dim = svg.get_dimensions()

            img = ImageSurface(
                FORMAT_ARGB32, width, height)
            ctx = Context(img)
            ctx.scale(width / dim.width, height / dim.height)
            svg.render_cairo(ctx)

            png_io = BytesIO()
            img.write_to_png(png_io)
            with open(output_file, 'wb') as fout:
                fout.write(png_io.getvalue())
            fout.close()
            svg.close()
            png_io.close()
            img.finish()
        else:
            with open(input_file, "r") as content_file:
                svg = content_file.read()
            content_file.close()
            fout = open(output_file, "wb")
            svg2png(bytestring=bytes(svg, "UTF-8"), write_to=fout)
            fout.close()
Beispiel #14
0
 def _draw(self):
     self.remove(self.canvas)
     self.draw()
     self.canvas = Gtk.Image().new_from_pixbuf(Rsvg.Handle().new_from_data(
         bytes(self.dwg.tostring(), 'ascii')).get_pixbuf())
     self.add(self.canvas)
     self.show_all()
     return True
Beispiel #15
0
def render_svg(svg):
  img = cairo.ImageSurface(cairo.FORMAT_ARGB32, 900, 900)
  ctx = cairo.Context(img)

  handle = Rsvg.Handle().new_from_data(svg.encode('utf-8'))
  handle.render_cairo(ctx)
  with io.BytesIO() as stream:
    img.write_to_png(stream)
    return stream.getvalue()
Beispiel #16
0
 def read_svg(self):
     try:
         handle = Rsvg.Handle()
         svg_path = ''.join(
             [os.path.join(res.PATH, 'icons', self.icon_name), '.svg'])
         self.svg = handle.new_from_file(svg_path)
     except:  # GError as error:
         print('No file found at {}.'.format(svg_path))
         self.svg = False
Beispiel #17
0
def clip(inputfile, outputfile, margin):
    name, x, y, width, height = get_bounding_box(inputfile)

    handle = Rsvg.Handle()
    svg = handle.new_from_file(inputfile)
    surface = cairo.SVGSurface(outputfile, width + margin * 2,
                               height + margin * 2)
    ctx = cairo.Context(surface)
    ctx.translate(-x + margin, -y + margin)
    svg.render_cairo(ctx)
    surface.finish()
Beispiel #18
0
def load_svgs(base_dir):
    piece_letters = "pnbrqk"
    for piece_type in range(chess.PAWN, chess.KING + 1):
        for piece_color in [chess.WHITE, chess.BLACK]:
            piece = chess.Piece(piece_type, piece_color)
            pl = piece_letters[piece_type - 1]
            sl = 'w' if piece_color == chess.WHITE else 'b'
            path = "%s%c_%c.svg" % (base_dir, sl, pl)
            index = piece_image_index(piece)
            handle = Rsvg.Handle()
            G.piece_images[index] = handle.new_from_file(path)
Beispiel #19
0
def collateA4():
    width,height =  595,842
    surfaces = [cairo.PDFSurface('./out/collate'+str(x+1)+'.pdf', width,height) for x in range(9)]
    contexts = [cairo.Context(surface) for surface in surfaces]
    handle = Rsvg.Handle()
    svgs = [handle.new_from_file(inp) for inp in ['./out/card'+str(x+1)+'.svg' for x in range(81)]]
    for i in range(81):
        dim = svgs[i].get_dimensions()
        contexts[i//9].save()
        contexts[i//9].translate(A4Positions[i%9][0],A4Positions[i%9][1])
        contexts[i//9].scale(192/dim.width,275/dim.height)
        svgs[i].render_cairo(contexts[i//9])
        contexts[i//9].restore()
Beispiel #20
0
def embed_svg(ifilename, ofilename):
    handle = rsvg.Handle()
    svg = handle.new_from_file(ifilename)
    dims = svg.get_dimensions()

    surface = cairo.PDFSurface(ofilename, dims.width, dims.height)
    ctx = cairo.Context(surface)
    svg.render_cairo(ctx)

    ctx.move_to(0, 0)
    ctx.line_to(dims.width, dims.height)
    ctx.set_source_rgb(1, 0, 0)
    ctx.stroke()
Beispiel #21
0
def svg_to_png(svg_path, png_path, width, height):
    svg = Rsvg.Handle().new_from_file(svg_path.as_posix())
    unscaled_width = svg.props.width
    unscaled_height = svg.props.height

    svg_surface = cairo.SVGSurface(None, width, height)
    svg_context = cairo.Context(svg_surface)
    svg_context.save()
    svg_context.scale(width / unscaled_width, height / unscaled_height)
    svg.render_cairo(svg_context)
    svg_context.restore()

    svg_surface.write_to_png(png_path.as_posix())
    svg_surface.finish()
def draw(ctx, surface_marking: SurfaceMarking):
    ctx.save()

    if (surface_marking.kind == SurfaceMarking.LEFT_TURN_MARKING
            or surface_marking.kind == SurfaceMarking.RIGHT_TURN_MARKING):
        ctx.translate(surface_marking.center.x, surface_marking.center.y)
        ctx.rotate(surface_marking.orientation)
        image_file = os.path.join(
            os.environ.get("KITCAR_REPO_PATH"),
            "kitcar-gazebo-simulation",
            "simulation",
            "models",
            "meshes",
            f"Fahrbahnmarkierung_Pfeil_" + (
                "L" if surface_marking.kind !=
                SurfaceMarking.LEFT_TURN_MARKING  # Weird
                else "R") + ".svg",
        )
        svg = Rsvg.Handle().new_from_file(image_file)
        ctx.scale(0.001, 0.001)
        svg.render_cairo(ctx)

    if (surface_marking.kind == SurfaceMarking.GIVE_WAY_LINE
            or surface_marking.kind == SurfaceMarking.STOP_LINE):
        ctx.translate(surface_marking.center.x, surface_marking.center.y)
        ctx.rotate(surface_marking.orientation)

        v = 0.5 * Vector(surface_marking.width, 0)
        line = MarkedLine(
            [-1 * v, v],
            style=(RoadSection.DASHED_LINE_MARKING
                   if surface_marking.kind == SurfaceMarking.GIVE_WAY_LINE else
                   RoadSection.SOLID_LINE_MARKING),
        )

        utils.draw_line(
            ctx,
            line,
            line_width=0.04,
            dash_length=0.08,
            dash_gap=0.06,
        )
    if surface_marking.kind == SurfaceMarking.START_LINE:
        draw_start_lane(ctx, surface_marking.frame)
    if surface_marking.kind == SurfaceMarking.ZEBRA_CROSSING:
        draw_zebra_crossing(ctx, surface_marking.frame)
    if surface_marking.kind == SurfaceMarking.PARKING_SPOT_X:
        draw_parking_spot_x(ctx, surface_marking.frame)

    ctx.restore()
Beispiel #23
0
 def set_image_white(self):
     handle = Rsvg.Handle()
     svg_path = ''.join([
         os.path.join(res.PATH, 'icons', self.icon_name), '_white', '.svg'
     ])
     self.svg_white = handle.new_from_file(svg_path)
     icon_size = self.get_icon_size()
     pixbuf = self.svg_white.get_pixbuf()
     if icon_size:
         pixbuf = pixbuf.scale_simple(icon_size, icon_size, 3)
     self.image.set_from_data(pixbuf.get_pixels(),
                              Cogl.PixelFormat.RGBA_8888,
                              pixbuf.get_width(), pixbuf.get_height(),
                              pixbuf.get_rowstride())
Beispiel #24
0
def collatedBack():
    width, height = 595.27559, 841.88976
    surface = cairo.PDFSurface('./out/back_print_4x4.pdf', width, height)
    context = cairo.Context(surface)
    handle = Rsvg.Handle()
    svg = handle.new_from_file('card_back_4x4.svg')
    dim = svg.get_dimensions()

    for i in range(9):
        context.save()
        context.translate(width - A4Positions[i][0] - 185, A4Positions[i][1])
        context.scale(185 / dim.width, 266 / dim.height)
        svg.render_cairo(context)
        context.restore()
Beispiel #25
0
def clip(inputfile, outputfile):
    name, x, y, width, height = get_bounding_box(inputfile)

    bigger_size = max(width, height)
    width_diff = (bigger_size - width) / 2
    height_diff = (bigger_size - height) / 2

    handle = Rsvg.Handle()
    svg = handle.new_from_file(inputfile)
    surface = cairo.SVGSurface(outputfile, bigger_size, bigger_size)
    ctx = cairo.Context(surface)
    ctx.translate(-x + width_diff, -y + height_diff)
    svg.render_cairo(ctx)
    surface.finish()
Beispiel #26
0
def svg_to_png(infile, outfile, dpi=300):
    import cairo
    import gi
    gi.require_version('Rsvg', '2.0')
    from gi.repository import Rsvg

    handle = Rsvg.Handle()
    svg = handle.new_from_file(infile)
    svg.set_dpi(dpi)
    dim = svg.get_dimensions()
    w, h = dim.width, dim.height
    img =  cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h)
    ctx = cairo.Context(img)
    svg.render_cairo(ctx)
    img.write_to_png(outfile)
Beispiel #27
0
def render(renderer, ctx):
    if renderer.rc.qrcode_text:
        qrcode_text = renderer.rc.qrcode_text
    else:
        qrcode_text = renderer.rc.origin_url

    if not qrcode_text:
        return

    x = convert_pt_to_dots(renderer._map_coords[0], renderer.dpi)
    y = convert_pt_to_dots(renderer._map_coords[1], renderer.dpi)
    w = convert_pt_to_dots(renderer._map_coords[2], renderer.dpi)
    h = convert_pt_to_dots(renderer._map_coords[3], renderer.dpi)
    W = convert_pt_to_dots(renderer.paper_width_pt)

    size = convert_pt_to_dots(
        max(renderer.paper_width_pt, renderer.paper_height_pt),
        renderer.dpi) / 12

    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )

    qr.add_data(qrcode_text)
    qr.make(fit=True)

    img = qr.make_image(image_factory=qrcode.image.svg.SvgPathFillImage,
                        fill_color='lightblue')
    svgstr = BytesIO()
    img.save(svgstr)

    svg_val = svgstr.getvalue()

    rsvg = Rsvg.Handle()
    svg = rsvg.new_from_data(svg_val)
    svgstr.close()

    ctx.save()
    ctx.translate(x + w - size, y + h - size)
    ctx.move_to(0, 0)
    factor = size / svg.props.height
    ctx.scale(factor, factor)
    svg.render_cairo(ctx)
    ctx.restore()
Beispiel #28
0
    def _marker(self, color, txt, lat, lon, ctx, dpi):

        marker_path = os.path.abspath(
            os.path.join(os.path.dirname(__file__), '..', '..', 'images',
                         'marker.svg'))

        fp = open(marker_path, 'r')
        data = fp.read()
        fp.close()

        if color[0] != '#':
            c = Color(color)
            color = c.hex_l

        data = data.replace('#000000', color)

        rsvg = Rsvg.Handle()
        svg = rsvg.new_from_data(data.encode())

        x, y = self._latlon2xy(lat, lon, dpi)

        scale = (50.0 / svg.props.height) * (dpi / 72.0)

        x -= svg.props.width * scale / 2
        y -= svg.props.height * scale

        ctx.save()
        ctx.translate(x, y)

        ctx.scale(scale, scale)
        svg.render_cairo(ctx)

        pc = PangoCairo.create_context(ctx)
        layout = PangoCairo.create_layout(ctx)
        fd = Pango.FontDescription('Droid Sans')
        fd.set_size(Pango.SCALE)
        layout.set_font_description(fd)
        layout.set_text(txt, -1)
        draw_utils.adjust_font_size(layout, fd, svg.props.width / 3,
                                    svg.props.width / 3)
        ink, logical = layout.get_extents()
        ctx.translate(svg.props.width / 2 - logical.width / svg.props.height,
                      svg.props.height / 5)
        PangoCairo.update_layout(ctx, layout)
        PangoCairo.show_layout(ctx, layout)

        ctx.restore()
Beispiel #29
0
    def _size_allocate_cb(self, widget, allocation):
        """We know the size of the widget on the screen, so we keep
        the parameters which are important for our rendering (center
        of the clock, radius).
        """
        # This callback can be called when the gdk window is not yet
        # set
        if self.window is None:
            return

        # Store the measures of the clock face widget
        self._center_x = int(allocation.width / 2.0)
        self._center_y = int(allocation.height / 2.0)
        self._radius = max(min(int(allocation.width / 2.0),
                           int(allocation.height / 2.0)) - 20, 0)
        self._line_width = int(self._radius / 150)

        cr = self.window.cairo_create()

        # Draw simple clock background
        self._simple_background_cache = cr.get_target().create_similar(
            cairo.CONTENT_COLOR_ALPHA, self._radius * 2,
            self._radius * 2)
        cache_ctx = cairo.Context(self._simple_background_cache)
        self._draw_simple_background(cache_ctx)
        self._draw_numbers(cache_ctx)

        # Reload the svg handle
        self._svg_handle = Rsvg.Handle(file="clock.svg")

        # Draw nice clock background
        self._nice_background_cache = cr.get_target().create_similar(
            cairo.CONTENT_COLOR_ALPHA, self._radius * 2,
            self._radius * 2)
        cache_ctx = cairo.Context(self._nice_background_cache)
        scale_x = self._radius * 2.0 / self._svg_handle.props.width
        scale_y = self._radius * 2.0 / self._svg_handle.props.height
        matrix = cairo.Matrix(xx=scale_x, yy=scale_y)
        cache_ctx.transform(matrix)
        self._svg_handle.render_cairo(cache_ctx)

        # The hands sizes are proportional to the radius
        self._hand_sizes['hour'] = self._radius * 0.5
        self._hand_sizes['minutes'] = self._radius * 0.8
        self._hand_sizes['seconds'] = self._radius * 0.7

        self.initialized = True
Beispiel #30
0
def convert_svg2png(infile, outfile, icon_size=None):
    """
        Converts svg files to png using Cairosvg or Inkscape
        @file_path : String; the svg file absolute path
        @dest_path : String; the png file absolute path
    """
    if not disable_svg2png:
        if use_inkscape:
            if icon_size:
                p = Popen([
                    "inkscape", "-z", "-f", infile, "-e", outfile, "-w",
                    str(icon_size), "-h",
                    str(icon_size)
                ],
                          stdout=PIPE,
                          stderr=PIPE)
            else:
                p = Popen(["inkscape", "-z", "-f", infile, "-e", outfile],
                          stdout=PIPE,
                          stderr=PIPE)
            p.communicate()
        else:
            if icon_size:
                handle = Rsvg.Handle()
                svg = handle.new_from_file(infile)
                dim = svg.get_dimensions()

                img = cairo.ImageSurface(cairo.FORMAT_ARGB32, icon_size,
                                         icon_size)
                ctx = cairo.Context(img)
                ctx.scale(icon_size / dim.width, icon_size / dim.height)
                svg.render_cairo(ctx)

                png_io = BytesIO()
                img.write_to_png(png_io)
                with open(outfile, 'wb') as fout:
                    fout.write(png_io.getvalue())
                svg.close()
                png_io.close()
                img.finish()
            else:
                with open(infile, "r") as content_file:
                    svg = content_file.read()
                fout = open(outfile, "wb")
                svg2png(bytestring=bytes(svg, "UTF-8"), write_to=fout)
                fout.close()