enceladus
Aug 18, 2017 - 09:38
We could use the designer(i.e. use the pyui file) to generate an image. Convert the view generated by pyui file to an image as folows. Open an image context with the view size as its size and draw image/text/shape based on the subviews as follows.
1. Draw ImageView as an image at its position
2. Draw label text as a string at its position
3. Draw buttons as shapes with their titles as shape names, background_color as fill color and border_color as stroke color.
(gist https://gist.github.com/a781c5f46e3292821f18736fd6f00ec7 )
import ui
import os
import math
def get_image(template_view):
x,y,w,h = template_view.frame
with ui.ImageContext(w,h) as ctx:
for t in template_view.subviews:
k = t.name
x,y,w,h = t.frame
if k.startswith('button'):
if t.title == 'oval':
path = ui.Path.oval(x,y,w,h)
elif t.title == 'rect':
path = ui.Path.rect(x,y,w,h)
elif t.title == 'rounded_rect':
path = ui.Path.rounded_rect(x,y,w,h, t.corner_radius)
else:
path = ui.Path()
ui.set_color(t.background_color)
path.fill()
path.line_width = t.border_width
ui.set_color(t.border_color)
path.stroke()
elif k.startswith('label'):
ui.draw_string(t.text, rect=(x,y,w,h), font=t.font,
color=t.text_color, alignment=t.alignment,
line_break_mode=t.line_break_mode)
elif k.startswith('imageview'):
t.image.draw(x,y,w,h)
return ctx.get_image()
def showimage_action(sender):
main_view.image.show()
filename = 'image_savefile.png'
def saveimage_action(sender):
img = main_view.image
with open(filename, 'wb') as fp:
fp.write(img.to_png())
def create_main_view(pyui_file):
template_view = ui.load_view(pyui_file)
x,y,w,h = template_view.frame
main_view = ui.ImageView(frame=(0,0,w,h), image=get_image(template_view))
main_view.right_button_items = [ui.ButtonItem(action=showimage_action, title='show'),
ui.ButtonItem(action=saveimage_action, title='save')]
return main_view
main_view = create_main_view('test1.pyui')
main_view.present('sheet')