コード例 #1
0
    def dots_touched(self):
        self.seq = ''
        for touch_id in self.touch_actives.keys():
            bn = self.touch_actives[touch_id][1]
            if bn not in self.seq:
                self.seq += bn
        self.seq = ''.join(sorted(self.seq))

        # display touched dots, symbol, Hirgana
        self.draw_dots(self['dots'], self.seq)
        if self.prefix != '':
            self.draw_dots(self['prefix_dots'], self.prefix)
            prefix_key = self.prefix + '|' + self.seq
            if prefix_key not in self.Japanese_Braille:
                # key could be no more an arab digit, remove prefix
                #self['prefix_dots'].hidden = True
                prefix_key = self.seq
        else:
            prefix_key = self.seq

        if prefix_key not in self.Japanese_Braille:
            temp_hirgana = '?'
        else:
            temp_hirgana = self.Japanese_Braille[prefix_key]
            if temp_hirgana == '()':
                if not self.parentheses:
                    temp_hirgana = temp_hirgana[0]
                else:
                    temp_hirgana = temp_hirgana[1]
            elif temp_hirgana == '「」':
                if not self.singular_quotation_marks:
                    temp_hirgana = temp_hirgana[0]
                else:
                    temp_hirgana = temp_hirgana[1]
            self['b_decision'].hidden = False

        # display not yet confirmed hirgana in hirganas field
        w1, h = ui.measure_string(self['hirganas'].text,
                                  font=self['hirganas'].font)
        w2, h = ui.measure_string(temp_hirgana,
                                  font=self['hirganas']['hirgana'].font)
        self['hirganas']['hirgana'].text = temp_hirgana
        self['hirganas']['hirgana'].x = w1
        self['hirganas']['hirgana'].width = w2
        self['dots'].x = self['hirganas'].x + self['hirganas']['hirgana'].x
        self['dots'].y = self['hirganas'].y + self['hirganas'].height
        if self.prefix != '':
            self['prefix_dots'].x = self['dots'].x - self['prefix_dots'].width
            self['prefix_dots'].y = self['dots'].y
        self['hirganas'].width = w1 + w2
コード例 #2
0
    def __init__(self,
                 text,
                 fill_color='lightgrey',
                 font_color='black',
                 font=('Apple SD Gothic Neo', 12),
                 **kwargs):

        self.text = text

        size = ui.measure_string(
            text,
            max_width=150,
            font=font,
            alignment=ui.ALIGN_CENTER,
        )
        outer = size + Size(32, 16)
        inner = size + Size(24, 8)
        super().__init__(outer,
                         fill_color='transparent',
                         line_color='transparent',
                         **kwargs)
        self.visible_background = sk.BoxNode(inner,
                                             fill_color=fill_color,
                                             no_body=True,
                                             parent=self)
        label = sk.LabelNode(text,
                             font=font,
                             font_color=font_color,
                             max_width=150,
                             line_break_mode=ui.LB_WORD_WRAP,
                             number_of_lines=0,
                             alignment=sk.LabelNode.ALIGN_CENTER,
                             vertical_alignment=sk.LabelNode.ALIGN_MIDDLE,
                             parent=self.visible_background)
        self.touch_enabled = True
コード例 #3
0
ファイル: uiView_context.py プロジェクト: HJvA/BLE-automation
 def draw_text(self, text, x, y, font_name=None, font_size=None):
     if font_size is None:
         font_size = self.font_size
     if font_name is None:
         font_name = self.font_name
     if TXTDRW:
         wl, hl = ui.measure_string(text, 0, font=(font_name, font_size))
         xo, yo = self.xyWorld(x, y)  #.whUser(wl,hl)
         frm = (xo, yo - hl, wl, hl)
         #logger.debug('txtdrw:%s:%s fnt:%s,%s' % (text,(frm),font_name,font_size) )
         ui.draw_string(text,
                        frm,
                        font=(font_name, font_size),
                        color='black',
                        alignment=ui.ALIGN_NATURAL,
                        line_break_mode=ui.LB_WORD_WRAP)
     else:
         lbl = ui.Label()
         lbl.font = (font_name, font_size)
         lbl.text = text
         lbl.alignment = ui.ALIGN_LEFT
         lbl.size_to_fit()
         wl, hl = lbl.width, lbl.height
         lbl.x, lbl.y = self.xyWorld(x, y)
         lbl.y -= hl
         self.inView.add_subview(lbl)
コード例 #4
0
 def get_wh(self):
     font_width, font_height = ui.measure_string(
         'a',
         font=('Menlo-Regular', self.stash.config.getint('display', 'TEXT_FONT_SIZE')))
     w = int(self.stash.ui.width / font_width)
     h = int(self.stash.ui.height / font_height)
     return (w, h)
コード例 #5
0
def VersionInStatusBar(version=False):	
	# called at begin of a script with version=text
	#           end                    version=False
	root, ext = os.path.splitext(sys.argv[0])  # script path without .py
	script_name = os.path.basename(root)  # script name without the path
	app = objc_util.UIApplication.sharedApplication()
	w = objc_util.ObjCClass('UIApplication').sharedApplication().keyWindow()
	main_view = w.rootViewController().view()
	bar = app.statusBar()
	b = bar.bounds()
	sv = bar.subviews()
	for v in sv:
		if v._get_objc_classname().startswith(b'SUILabel_PY3'):
			v.removeFromSuperview()
			del v
			if not version:		# remove version label 
				return
	lbl = ui.Label()
	lbl.frame = (200,2,23,16)
	lbl.text_color = 'blue'
	lbl.border_width = 1
	lbl.border_color = 'blue'
	lbl.font = ('Courier-Bold',12)
	lbl.text = script_name+': version='+version
	lbl.width = ui.measure_string(lbl.text,font=lbl.font)[0]
	lbl = lbl
	bar.addSubview_(lbl)
コード例 #6
0
    def draw(self):
        # set the button height - hack for now
        try:
            self.height = (self.superview.height - 5)
        except:
            pass

        # set the image height without text
        if self.image:
            self._image.width = self.width
            self._image.height = self.height

        if self.title:
            w, h = ui.measure_string(
                self._title.text,
                font=self.font,
                alignment=ui.ALIGN_CENTER,
            )

            self._title.frame = (0, (self.height - h), self.width, h)
            try:
                self._image.height -= (h + self.title_pad)
            except:
                print('failed to set image height')
                pass

            try:
                # Setup the Text to center in the view
                self._title.width = self.width
                self._title.alignment = ui.ALIGN_CENTER
            except:
                pass
コード例 #7
0
def adjust_for_platform() -> Tuple[int, Union[TPoolExType, PPoolExType], int]:
    if platform.system() == 'Darwin':
        if platform.machine().startswith('iPad'):
            device = "iPad"
        elif platform.machine().startswith('iP'):
            device = "iPhone"
        else:
            device = "mac"
    else:
        device = "other"

    if device in ("iPad", "iPhone"):
        # Adapt for smaller screen sizes in iPhone and iPod touch
        import ui
        import console
        console.clear()
        if device == 'iPad':
            font_size = IPAD_FONT_SIZE
        else:
            font_size = IPHONE_FONT_SIZE
        console.set_font(IOS_FONT, font_size)
        screen_width = ui.get_screen_size().width
        char_width = ui.measure_string('.', font=(IOS_FONT, font_size)).width
        line_width = int(screen_width / char_width - 1.5) - 1
        pool_ex = concurrent.futures.ThreadPoolExecutor
        workers = IOS_WORKERS
    else:
        line_width = shutil.get_terminal_size((80, 24)).columns
        pool_ex = concurrent.futures.ProcessPoolExecutor
        from multiprocessing import cpu_count
        workers = cpu_count() + 1

    return line_width, pool_ex, workers
コード例 #8
0
def SaveInFiles(file,
                w,
                h,
                mode='sheet',
                popover_location=None,
                callback=None,
                title=None):
    # view needed for picker
    uiview = ui.View()
    uiview.frame = (0, 0, w, h)
    if mode == 'sheet':
        uiview.present('sheet', hide_title_bar=True)
    elif mode == 'popover':
        if popover_location:
            uiview.present('popover',
                           hide_title_bar=True,
                           popover_location=popover_location)
        else:
            return
    else:
        return
    url = nsurl(file)
    urls = [url]
    UIDocumentPickerMode = 2  # 2 = UIDocumentPickerModeExportToService (copy)
    # 3 = UIDocumentPickerModeMoveToService   (move)⚠️
    UIDocumentPickerViewController = ObjCClass(
        'UIDocumentPickerViewController').alloc().initWithURLs_inMode_(
            urls, UIDocumentPickerMode)

    # Use new delegate class:
    delegate = MyUIDocumentPickerViewControllerDelegate.alloc().init()
    UIDocumentPickerViewController.delegate = delegate
    UIDocumentPickerViewController.setModalPresentationStyle_(
        3)  #currentContext
    UIDocumentPickerViewController.callback = callback  # used by delegate
    UIDocumentPickerViewController.uiview = uiview  # used by delegate

    # only to show it is possible to add controls on ViewController
    if title:
        l = ui.Label()
        wb = 100  # button width
        wl = uiview.width - 2 * wb  # title width
        #l.border_width = 1					# for tests only
        l.text = title
        # find greatest font size allowing to display title between buttons
        fs = 32
        while True:
            wt, ht = ui.measure_string(title, font=('Menlo', fs))
            if wt <= wl:
                break
            fs = fs - 1
        l.frame = (wb, 42, wl, 32)
        l.text_color = 'green'
        UIDocumentPickerViewController.view().addSubview_(ObjCInstance(l))

    objc_uiview = ObjCInstance(uiview)
    SUIViewController = ObjCClass('SUIViewController')
    vc = SUIViewController.viewControllerForView_(objc_uiview)
    vc.presentViewController_animated_completion_(
        UIDocumentPickerViewController, True, None)
コード例 #9
0
    def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
        font = 'Menlo', prop.get_size_in_points() * 1.1

        w, h = ui.measure_string(s,
                                 font=font,
                                 alignment=ui.ALIGN_RIGHT,
                                 line_break_mode=ui.LB_WORD_WRAP)
        y -= h
        if True or angle:
            with ui.GState():
                ui.concat_ctm(ui.Transform.translation(x, y))
                ui.concat_ctm(
                    ui.Transform.rotation(-angle * matplotlib.numpy.pi / 180.))
                ui.draw_string(s,
                               rect=(0, 0, 0, 0),
                               font=font,
                               color='black',
                               alignment=ui.ALIGN_RIGHT,
                               line_break_mode=ui.LB_WORD_WRAP)
        else:
            ui.draw_string(s,
                           rect=(x, y, 0, 0),
                           font=font,
                           color='black',
                           alignment=ui.ALIGN_RIGHT,
                           line_break_mode=ui.LB_WORD_WRAP)
コード例 #10
0
 def draw_face(self, diameter, border, font_size):
     with ui.ImageContext(diameter, diameter) as ctx:
         ui.set_color('white')
         circle = ui.Path.oval(border / 2, border / 2, diameter - border,
                               diameter - border)
         circle.line_width = border - 1
         circle.fill()
         ui.set_color('silver')
         with ui.GState():
             ui.set_shadow((0, 0, 0, 0.35), 0, 1, 5.0)
             circle.stroke()
         angle = (-pi / 2) + (pi * 2) / 12.0
         for i in range(1, 13):
             number = str(i)
             x = diameter / 2 + cos(angle) * (diameter / 2 -
                                              font_size * 1.2)
             y = diameter / 2 + sin(angle) * (diameter / 2 -
                                              font_size * 1.2)
             font = ('HelveticaNeue-UltraLight', font_size)
             w, h = ui.measure_string(number, font=font)
             rect = (x - 50, y - h / 2, 100, h)
             ui.draw_string(number,
                            rect=rect,
                            font=font,
                            alignment=ui.ALIGN_CENTER)
             angle += (pi * 2.0) / 12.0
         return ctx.get_image()
コード例 #11
0
ファイル: ComboBox.py プロジェクト: mcriley821/CustomUI
    def layout(self):
        sizes = [ui.measure_string(i, font=self.font) for i in self.choices]
        _row_w = max(self.width, max(i[0] for i in sizes))
        _row_h = max(i[1] for i in sizes) + 3

        # self layout
        if _row_w != self.width:
            self.width = _row_w + _row_h + 9
        if _row_h > self.height:
            self.height = _row_h

        # selected label layout
        self.selected_label.width = self.width - self.height - 6
        self.selected_label.height = self.height - 6

        # drop button layout
        self.drop_button.x = self.width - self.height
        self.drop_button.width = self.height - 3
        self.drop_button.height = self.height - 6

        # dropbox layout
        _h = _row_h * min(self.display_count, len(self.choices))
        self.dropbox.row_height = _row_h
        self.dropbox.width = self.selected_label.width
        self.dropbox.x = self.x + 3
        self.dropbox.y = self.y + self.height
        self.dropbox.height = _h
        self.dropbox.reload()
        self.dropbox.selected_row = self.selected_index
コード例 #12
0
 def show_Vocab(self, word, color):
     if word.find("(") > 0:
         line1 = word[0:word.find("(") - 1]
         line2 = word[word.find("("):]
         size1 = ui.measure_string(line1,
                                   max_width=0,
                                   font=(self.font, int(self.fontsize)),
                                   alignment=ui.ALIGN_LEFT,
                                   line_break_mode=ui.LB_WORD_WRAP)
         self.view.make_label('label1',
                              line1,
                              15,
                              int(self.fontsize),
                              size1[0],
                              int(self.fontsize),
                              self.font,
                              int(self.fontsize),
                              color=color)
         size2 = ui.measure_string(line2,
                                   max_width=0,
                                   font=(self.font, int(self.fontsize)),
                                   alignment=ui.ALIGN_LEFT,
                                   line_break_mode=ui.LB_WORD_WRAP)
         self.view.make_label('label2',
                              line2,
                              15,
                              int(self.fontsize) * 3,
                              size2[0],
                              int(self.fontsize),
                              self.font,
                              int(self.fontsize),
                              color=color)
     else:
         size = ui.measure_string(word,
                                  max_width=0,
                                  font=(self.font, int(self.fontsize)),
                                  alignment=ui.ALIGN_LEFT,
                                  line_break_mode=ui.LB_WORD_WRAP)
         self.view.make_label('label1',
                              word,
                              15,
                              int(self.fontsize),
                              size[0],
                              int(self.fontsize),
                              self.font,
                              int(self.fontsize),
                              color=color)
コード例 #13
0
def make_label(text, font, alignment, background_color, x, y):
    w, h = ui.measure_string(text, 
                font=font, alignment=alignment, max_width=0)
    #print(w,h)
    label = ui.Label(text=text,
                font=font, alignment=alignment, 
                background_color=background_color, frame=(x,y,w,h), border_width=1)
    return label
コード例 #14
0
 def draw_hirganas(self):
     w, h = ui.measure_string(self['hirganas'].text,
                              font=self['hirganas'].font)
     self['hirganas'].width = w
     self['hirganas'].x = (self.width - w) / 2
     self[
         'b_conversion'].x = self['hirganas'].x - self['b_conversion'].width
     self['b_conversion'].hidden = len(self.hirganas) == 0
コード例 #15
0
    def conversion_button_action(self, sender):
        t = self['hirganas'].text
        items = [t]
        try:
            self.cursor.execute(
                'select hiragana, kanji from Hiragana_to_Kanji where hiragana = ?',
                (t, ))
        except Exception as e:
            console.hud_alert(
                'be sure that HiraganaToKanji.db file is present', 'error', 3)

        for li in self.local_kanjis:
            s = li.split('\t')
            try:
                if t not in s[0]:
                    continue
                items.append(s[1])
                break
            except Exception as e:
                # lome could be erroneously typed
                continue

        w_max = 0
        for row in self.cursor:
            t = row[1]
            items.append(t)
        for t in items:
            w, h = ui.measure_string(t, font=self['kanjis'].data_source.font)
            w_max = max(w_max, w + 50)
        sender.hidden = True
        self['kanjis'].data_source.items = items
        if len(items) == 1:
            self.tableview_did_select(self['kanjis'], 0, 0)
            return
        # Kanji's exist, display a TableView
        self['kanjis'].x = (self.width - w_max) / 2
        self['kanjis'].width = w_max
        self['kanjis'].height = min(self.bounds.size[1] - (2 + 32 + 2),
                                    len(items) * self['kanjis'].row_height)
        #self['kanjis'].hidden = False
        x = self['kanjis'].x + self['kanjis'].width + 10
        #self['kanjis_up'].hidden = False
        self['kanjis_up'].x = x
        #self['kanjis_ok'].hidden = False
        self['kanjis_ok'].x = x
        #self['kanjis_other'].hidden = False												# add 1.6
        e_b = self['kanjis_ok'].y - self['kanjis_up'].y - self[
            'kanjis_other'].height  # add 1.6
        self['kanjis_other'].x = self['kanjis'].x - self[
            'kanjis_other'].width - e_b  # add 1.6
        #self['kanjis_down'].hidden = False
        self['kanjis_down'].x = x
        self.hide_buttons(False)
        self['kanjis'].current = 0
        ui.delay(self.tableview_say_current, 0.01)
        self['kanjis_ok'].title = self.select_text + self.get_kanji(0)
        self['kanjis_other'].title = self.select_text + self.get_kanji(
            0, next_sentence=True)  # add 1.9
コード例 #16
0
	def get_max_fontsize(r, text, font_name, inset_rect = ui.Rect()):
		r1 = ui.Rect(*r).inset(*inset_rect)
		for i in xrange(5, 1000):
			w, h = ui.measure_string(text, max_width=0,
			font=(font_name, i), alignment=ui.ALIGN_LEFT,
			line_break_mode=ui.LB_TRUNCATE_TAIL)
			
			if w > r1.width or h > r1.height:
				return (i - 1, ui.Rect(r1.x, r1.y, w, h))
コード例 #17
0
    def update_texture(self):
        if self._suspend_updates:
            return
        w, h = ui.measure_string(self.text, font=self.font)

        with ui.ImageContext(max(w, 1), max(h, 1)) as ctx:
            ui.draw_string(self.text, (0, 0, w, h), self.font, color='white')
            img = ctx.get_image()
        self.texture = Texture(img)
        self._rendered_text = self.text
コード例 #18
0
    def draw(self):
        # redraw button
        def darken(color):
            return tuple([0.5 * x for x in color])

        #set up button size to fit.
        padding = 10
        textsize = ui.measure_string(string=self.title,
                                     max_width=0,
                                     font=self.font,
                                     alignment=ui.ALIGN_CENTER)

        #draw border
        ui.set_color(self.border_color)
        path = ui.Path.rounded_rect(0, 0, self.width, self.height,
                                    self.corner_radius)
        path.line_width = self.border_width
        path.stroke()

        #fill button, depending on touch state
        if self.touched:
            if self.doing_longtouch:
                ui.set_color('blue')
            else:
                ui.set_color('grey')
        else:
            ui.set_color(self.bg_color)
        path.fill()

        # fill corner darker, if has children
        if self.flow.subviews:
            corner = ui.Path()
            corner.move_to(self.width - 1.5 * self.corner_radius, 0)
            corner.line_to(self.width, 0)
            corner.line_to(self.width, 1.5 * self.corner_radius)
            corner.line_to(self.width - 1.5 * self.corner_radius, 0)
            ui.set_color(darken(darken(self.bg_color)))
            corner.stroke()
            corner.fill()

        # draw title, center vertically, horiz
        rect = list(self.bounds)
        rect[1] = (rect[3] - textsize[1]) / 2  #vert center
        rect[2] = max(rect[2], textsize[0] + 10)
        ui.draw_string(self.title,
                       rect=tuple(rect),
                       font=self.font,
                       color=self.tint_color,
                       alignment=ui.ALIGN_CENTER,
                       line_break_mode=ui.LB_WORD_WRAP)

        if textsize[0] > self.bounds[2]:
            self.width = textsize[0] + 10
コード例 #19
0
    def __init__(self, key, value=False, text=None, imgsize=26, **kwargs):
        def b64i(data):
            if isinstance(data, list):
                data = ''.join(data)

            d = b64decode(data)
            return ui.Image.from_data(d)

        # Strictly to make it fit in Pythonista
        def c(which):
            return self.checkboxes[which]

        def getopt(opt):
            pass

        unchecked = b64i(c('unchecked'))
        checked = b64i(c('checked'))

        # Checkbox Options

        self.value = value
        button = ui.Button()
        button.width = imgsize
        button.height = imgsize
        button.value = value
        button.flex = 'TBR'
        button.name = key
        button.tint_color = '#000'
        button.text = text

        state = {True: checked, False: unchecked}
        button.image = state[value]

        def chgbtn(sender):
            self.value = not self.value
            sender.image = state[self.value]

        button.action = chgbtn

        self.add_subview(button)

        if text:
            t = ui.Label()
            t.text = text
            tw = ui.measure_string(t.text, font=t.font)
            t.flex = 'W'
            bw = (imgsize + tw[0] + 5)
            t.x = imgsize + 5
            t.height = imgsize - round(imgsize / 10)
            self.add_subview(t)
            self.frame = (5, 5, bw, imgsize)
            self.height = 26
コード例 #20
0
ファイル: love.py プロジェクト: xalgord/python
def write(self, text, move=True, align="center", font=None):
    text = str(text)
    w, h = ui.measure_string(text)
    color = "self._current_color"
    pos = self._pos

    def _draw():
        ui.draw_string(text, (pos.x, pos.y - h, 0, 0), color=color)

    self._add_drawing(_draw)
    if move:
        self._pos += (w, 0)
    self.update_view()
コード例 #21
0
    def __init__(self):
        # Initialize the pyte screen based on the current screen size
        font_width, font_height = ui.measure_string(
            'a',
            font=('Menlo-Regular', _stash.config.getint('display', 'TEXT_FONT_SIZE')))
        # noinspection PyUnresolvedReferences
        self.screen = pyte.screens.DiffScreen(
            int(_stash.ui.width / font_width),
            int(_stash.ui.height / font_height)
        )
        self.stream = pyte.Stream()
        self.stream.attach(self.screen)

        self.client = None
コード例 #22
0
 def update_texture(self):
     if self._suspend_updates:
         return
     w, h = ui.measure_string(self.text, font=self.font)
     # Round up size to next multiple of screen scale
     # (makes it easier to get crisp rendering in common cases)
     s = get_screen_scale()
     w = math.ceil(w / s) * s
     h = math.ceil(h / s) * s
     with ui.ImageContext(max(w, 1), max(h, 1)) as ctx:
         ui.draw_string(self.text, (0, 0, w, h), self.font, color='white')
         img = ctx.get_image()
     self.texture = Texture(img)
     self._rendered_text = self.text
コード例 #23
0
	def __init__(self):
		self.close = False
		_stash.stashssh = self
		# Initialize the pyte screen based on the current screen size
		font = ('Menlo-Regular', _stash.config.getint('display',
								'TEXT_FONT_SIZE'))
		font_width, font_height = ui.measure_string('a', font=font)
		# noinspection PyUnresolvedReferences
		self.screen = pyte.screens.DiffScreen(
				int(_stash.ui.width / font_width),
				int(_stash.ui.height / font_height))
		self.stream = pyte.Stream()
		self.stream.attach(self.screen)
		try:
			self.client = _stash.csc_ssh
		except:
			raise Exception('Error')
コード例 #24
0
    def get_max_fontsize(self):
        # would love some ideas for to clean this up
        # i could snapshot the params, and compare on each call. yuk
        # the loop is stupid
        r = ui.Rect(*self.rect).inset(*self.margin)
        last_w = last_h = 0

        for i in range(5, 1000):
            w, h = ui.measure_string(self.text,
                                     max_width=0,
                                     font=(self.font_name, i),
                                     alignment=ui.ALIGN_CENTER,
                                     line_break_mode=ui.LB_TRUNCATE_TAIL)

            if w > r.width or h > r.height:
                return (i - 1, ui.Rect(0, 0, last_w, last_h))

            last_w, last_h = w, h
コード例 #25
0
    def __init__(self):
        with open('words_en.data') as f:
            self.words = marshal.load(f)
        self.root = sk.Node()
        self.add_child(self.root)
        self.background_color = '#0b1d28'
        textures = {}
        for letter in letter_freq:
            with ui.ImageContext(tile_size, tile_size) as ctx:
                shadow = ui.Path.rounded_rect(2, 2, tile_size - 4,
                                              tile_size - 4, 5)
                ui.set_color('silver')
                shadow.fill()

                bg = ui.Path.rounded_rect(2, 2, tile_size - 4, tile_size - 8,
                                          5)
                ui.set_color('white')
                bg.fill()
                font = ('AvenirNext-Regular', font_size)
                w, h = ui.measure_string(letter.upper(), font=font)
                x, y = (tile_size - w) / 2, (tile_size - h) / 2
                ui.draw_string(letter.upper(),
                               rect=(x, y, w, h),
                               font=font,
                               color='black')
                textures[letter] = sk.Texture(ctx.get_image())
        self.tile_textures = textures
        self.tiles = []  #[[None]*rows for i in xrange(cols)]
        for x, y in product(xrange(cols), xrange(rows)):
            s = self.create_tile(x, y)
            self.tiles.append(s)
            self.root.add_child(s)
        self.selected = []
        self.touched_tile = None
        self.score_label = sk.LabelNode()
        self.score_label.font_name = 'AvenirNext-Regular'
        self.score_label.font_size = 50
        self.score_label.h_align = sk.H_ALIGN_CENTER
        self.score_label.text = '0'
        self.score = 0
        self.add_child(self.score_label)
        self.did_change_size(None)
コード例 #26
0
    def __init__(self):
        with open('words_en.data') as f:
            self.words = marshal.load(f)
        self.root = sk.Node()
        self.did_change_size(None)
        self.add_child(self.root)
        self.background_color = '#0b1d28'
        textures = {}
        for letter in letter_freq:
            with ui.ImageContext(tile_size, tile_size) as ctx:
                shadow = ui.Path.rounded_rect(0, 0, tile_size, tile_size, 5)
                ui.set_color('silver')
                shadow.fill()
                bg = ui.Path.rounded_rect(0, 0, tile_size, tile_size - 4, 5)
                ui.set_color('white')
                bg.fill()
                font = ('AvenirNext-Regular', font_size)
                w, h = ui.measure_string(letter.upper(), font=font)
                x, y = (tile_size - w) / 2, (tile_size - h) / 2
                ui.draw_string(letter.upper(),
                               rect=(x, y, w, h),
                               font=font,
                               color='black')
                textures[letter] = sk.Texture(ctx.get_image())
        self.tile_textures = textures

        self.tiles = [[None] * rows for i in xrange(cols)]
        for x, y in product(xrange(cols), xrange(rows)):
            letter = choice(letter_bag)
            s = sk.SpriteNode(self.tile_textures[letter])
            s.user_info = {'letter': letter, 'x': x, 'y': y}
            pos_x = tile_size / 2 + x * (tile_size + padding)
            pos_y = tile_size / 2 + y * (tile_size + padding)
            if x % 2 != 0:
                pos_y += tile_size / 2
            s.position = pos_x, pos_y
            s.color_blend_factor = 1
            s.color = 'white'
            self.tiles[x][y] = s
            self.root.add_child(s)
        self.selected = []
        self.touched_tile = None
コード例 #27
0
def font_size_for_rect(rect, text, font_name, inset_factor=0.0):
    fs_size = 0

    # inset the rect, by a factor for width and height
    # the inset can be very helpful
    inset_rect = ui.Rect(rect.width * inset_factor, rect.height * inset_factor)

    r = ui.Rect(*rect).inset(*inset_rect)

    for fs in xrange(0, 1000):
        fw, fh = ui.measure_string(text,
                                   max_width=0,
                                   font=(font_name, fs),
                                   alignment=ui.ALIGN_LEFT,
                                   line_break_mode=ui.LB_TRUNCATE_TAIL)

        if fw > r.width or fh > r.height:
            fs_size = fs - 1
            break
    return fs_size
コード例 #28
0
    def draw_text(self, **kwargs):
        if kwargs:
            self.do_kwargs(**kwargs)

        r = ui.Rect(*self.rect).inset(*self.margin).translate(*self.origin)

        my_center = r.center()
        font_size = self.font_size

        if not font_size:
            result = self.get_max_fontsize()
            r1 = ui.Rect(*result[1])
            font_size = result[0]
        else:
            w, h = ui.measure_string(self.text,
                                     max_width=0,
                                     font=(self.font_name, font_size),
                                     alignment=ui.ALIGN_CENTER,
                                     line_break_mode=ui.LB_TRUNCATE_TAIL)
            r1 = ui.Rect(0, 0, w, h)

        r1.center(my_center)
        with ui.GState():
            if self.rotate:
                '''
				help from @omz
				https://forum.omz-software.com/topic/3180/understanding-ui-transform-rotation
				'''
                ui.concat_ctm(ui.Transform.translation(*r1.center()))
                ui.concat_ctm(ui.Transform.rotation(math.radians(self.rotate)))
                ui.concat_ctm(ui.Transform.translation(*r1.center() * -1))

            if self.use_shadow:
                ui.set_shadow(*self.shadow_params)

            ui.draw_string(self.text,
                           rect=r1,
                           font=(self.font_name, font_size),
                           color=self.text_color,
                           alignment=ui.ALIGN_CENTER,
                           line_break_mode=ui.LB_TRUNCATE_TAIL)
コード例 #29
0
	def layout(self):
		import ui
		#print('layout')
		# supports changing orientation
		#print(ui.get_screen_size())
		dx = 8
		dy = 2
		x0 = 15
		y0 = 10
		dx_middle = 25 
		y = y0
		x = x0
		w_button = (ui.get_screen_size()[0] - 2*x0 - 17*dx - dx_middle)/18
		for pad_elem in self.pad:
			nw = pad_elem.get('width', 1)
			wb = w_button*nw + dx*(nw-1)
			if (x + wb + dx) > self.width:
				y = y + self.h_button + dy
				x = x0
			if pad_elem['key'] == 'nul':					# let free space	
				x = x + wb + dx	
				continue
			elif pad_elem['key'] == 'new row':		# new row
				y = y + self.h_button + dy
				x = x0
				continue
			button = self[pad_elem['key']]
			xb = x + dx_middle if (x+wb) > self.width/2 else x
			button.frame = (xb,y,wb,self.h_button)
			if button.title != '':
				font_size = self.h_button - 8
				while True:
					d = ui.measure_string(button.title,font=(button.font[0],font_size))[0]+4
					if d <= wb:
						break
					font_size = font_size - 1			
			button.font = (button.font[0],font_size)
			x = x + wb + dx
		self.height = y + self.h_button + dy	
コード例 #30
0
    def draw_label(self):
        if not self.drawing_on: return
        if not self.label_on: return

        cr = ui.Rect(*self.bounds)
        ui.set_color('purple')
        s = str('{:.0%}'.format(self.v))

        dim = ui.measure_string(s,
                                max_width=cr.width,
                                font=self.font,
                                alignment=ui.ALIGN_CENTER,
                                line_break_mode=ui.LB_TRUNCATE_TAIL)

        lb_rect = ui.Rect(0, 0, dim[0], dim[1])
        lb_rect.center(cr.center())

        ui.draw_string(s,
                       lb_rect,
                       font=self.font,
                       color='black',
                       alignment=ui.ALIGN_CENTER,
                       line_break_mode=ui.LB_TRUNCATE_TAIL)