Starting from @omz sketch example, i have modified it (see below) to:
- have a smaller view.
- not start in 0,0.
My goal is to have several distinct areas on the screen where i can draw into, not just 1big area.
# SketchView
# this class provides a container for hand drawing
import ui
# The PathView class is responsible for tracking
# touches and drawing the current stroke.
# It is used by SketchView.
class PathView (ui.View):
def __init__(self, frame):
self.frame = frame
self.path = None
def touch_began(self, touch):
x, y = touch.location
self.path = ui.Path()
self.path.line_width = 8
self.path.line_join_style = ui.LINE_JOIN_ROUND
self.path.line_cap_style = ui.LINE_CAP_ROUND
self.path.move_to(x, y)
def touch_moved(self, touch):
x, y = touch.location
self.path.line_to(x, y)
self.set_needs_display()
def touch_ended(self, touch):
# Send the current path to the SketchView:
if callable(self.onTouchEnded):
self.onTouchEnded(self)
# Clear the view (the path has now been rendered
# into the SketchView's image view):
self.path = None
def draw(self):
if self.path:
self.path.stroke()
class SketchView (ui.View):
def __init__(self, frame, background_color='white'):
self.background_color = background_color
self.frame = frame
# the image manager
iv = ui.ImageView(frame=self.bounds)
self.image_view = iv
self.add_subview(iv)
# the path manager
pv = PathView(frame=self.bounds)
pv.onTouchEnded = self.savePathToImage
self.add_subview(pv)
def savePathToImage(self, sender):
path = sender.path
old_img = self.image_view.image
width, height = self.image_view.width, self.image_view.height
with ui.ImageContext(width, height) as ctx:
if old_img:
old_img.draw()
path.stroke()
self.image_view.image = ctx.get_image()
# you must have a global view to embed the sketch views
gv = ui.View(background_color='white')
gv.present('fullscreen')
# now creat 1 sketch view
sv = SketchView(frame=(100,100,512,512), background_color='pink')
gv.add_subview(sv)
# and a second one
sv2 = SketchView(frame=(700, 100, 300, 300), background_color='cyan')
gv.add_subview(sv2)