Kivy - SVGs



The Kivy framework supports displaying the SVG files, although it is still highly experimental at this stage. In computer graphics, SVG stands for Scalable Vector Graphics, a standard defined by W3 Consortium, for encoding the image data.

The image formats such as PNG and JPG are based upon raster graphics, in which the image data is stored in the form of a bitmap, which is a grid of color and location of pixels. The downside of this format is that if the image is magnified, the image starts blurring after a certain point.

On the other hand, a vector graphics image is stored mathematically as a series of XML instructions, with which the image is drawn on the screen. that tell a viewing program how to "draw" the image on your screen. The drawing can take place at any size because SVG files are resolution independent. They can be scaled up or down without any drop in quality or sharpness.

Kivy library defines Svg class in the "kivy.graphics.svg" module. To draw a SVG image on the canvas of any widget we can use following syntax −

from kivy.graphics.svg import Svg
with widget.canvas:
   svg = Svg("test.svg")

The Svg class has the following properties −

  • anchor_x − Horizontal anchor position for scaling and rotations. Defaults to 0. Values 0,1, and 2 correspond to 'left', 'center' and 'right'.

  • anchor_y − Vertical anchor position for scaling and rotations. Defaults to 0. Values 0,1, and 2 correspond to 'left', 'center' and 'right'.

  • color − The default color used for SvgElements that specify "currentColor"

  • height − 'double'

  • source − SVG Filename / source to load.

  • width − 'double'

Example

The following program uses a "kv" script to load a Scatter widget. An "svg" object is placed in a GridLayout. Give the name of the file as its source property. Here is the "kv" file −

<SvgWidget>:
   do_rotation: True
<FloatLayout>:
   canvas.before:
      Color:
         rgb: (1, 1, 1)
      Rectangle:
         pos: self.pos
         size: self.size

Python code for Kivy App class −

from kivy.uix.scatter import Scatter
from kivy.app import App
from kivy.graphics.svg import Svg
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder
from kivy.core.window import Window

Window.size = (720,400)

class SvgWidget(Scatter):
   def __init__(self, filename):
      super(SvgWidget, self).__init__()
      with self.canvas:
         svg = Svg(source=filename)
      self.size = Window.width, Window.height
      
class SvgDemoApp(App):
   def build(self):
      self.root = GridLayout(cols=1)
      
      filename = "ship.svg"
      svg = SvgWidget(filename)

      self.root.add_widget(svg)
      svg.scale = 4

SvgDemoApp().run()

Output

When you run this program, it will produce the following output window −

Kivy Svgs
Advertisements