Задание:
Разработайте расширение Inkscape для создания циферблата
часов.
Исходные данные, которые
расширение должно запрашивать у пользователя:
Расширение должно в центре листа рисовать циферблат часов по заданным параметрам.
Пример:
Пример расширения для
вывода текста:
hello_world.inx
<?xml version="1.0" encoding="windows-1251"?>
<inkscape-extension>
<_name>Hello World!</_name>
<id>org.ekips.filter.hello_world</id>
<dependency type="executable" location="extensions">hello_world.py</dependency>
<dependency type="executable" location="extensions">inkex.py</dependency>
<param name="what" type="string" _gui-text="Text:">World</param>
<param name="redcolor" type="boolean" _gui-text="Click if red:">false</param>
<effect>
<object-type>all</object-type>
<effects-menu>
<submenu _name="Examples"/>
</effects-menu>
</effect>
<script>
<command reldir="extensions" interpreter="python">hello_world.py</command>
</script>
</inkscape-extension>
hello_world.py
# -*- coding: windows-1251 -*-
#!/usr/bin/env python
import sys
sys.path.append('/usr/share/inkscape/extensions')
import inkex
from simplestyle import *
class HelloWorldEffect(inkex.Effect):
def __init__(self):
inkex.Effect.__init__(self)
# определяем строковый параметр "--what" с коротким названием "-w" и значением по умолчанию "World".
self.OptionParser.add_option('-w', '--what', action = 'store',
type = 'string', dest = 'what', default = 'World',
help = 'Text')
# определяем параметр логического типа "--redcolor" с коротким названием "-r" и значением по умолчанию "false".
self.OptionParser.add_option('-r', '--redcolor', action = 'store',
type = 'inkbool', dest = 'redcolor', default = 'false',
help = 'Red color?')
def effect(self):
# получаем значение параметра "--what"
what = self.options.what
# получаем значение параметра "--redcolor"
redcolor = self.options.redcolor
# получаем в переменную svg указатель для доступа к главному SVG элементу документа
svg = self.document.getroot()
# и с его помощью получаем ширину и высоту листа (это можно сделать по-разному, см. ниже):
width = inkex.unittouu(svg.get('width'))
height = inkex.unittouu(svg.attrib['height'])
# создаем новый слой
layer = inkex.etree.SubElement(svg, 'g')
#задаем слою название MyLayer
layer.set(inkex.addNS('label', 'inkscape'), 'MyLayer')
layer.set(inkex.addNS('groupmode', 'inkscape'), 'layer')
# создаем текстовый элемент
text = inkex.etree.Element(inkex.addNS('text','svg'))
# задаем текстовое значение для вывода в текстовом элементе (заодно делаем перекодировку, чтобы русские буквы корректно отображались)
text.text = unicode('Hello '+what+'!','windows-1251')
# задаем координаты текста (в центр экрана)
text.set('x', str(width / 2))
text.set('y', str(height / 2))
# проверяем, в какой цвет окрасить (черный по умолчанию)
if redcolor:
col="red"
else:
col="black"
# задаем нужные стили (в том числе и цвет текста
style = {'text-align' : 'center', 'text-anchor': 'middle', 'fill':col, 'font-size':'100px'}
# применяем стили
text.set('style', formatStyle(style))
# добавляем текст в слой
layer.append(text)
# Create effect instance and apply it.
effect = HelloWorldEffect()
effect.affect()