class CounterNum(Widget): label = ObjectProperty(None) texture_size = None label_texture = ObjectProperty(None) def __init__(self, num, **kwargs): super(CounterNum, self).__init__(**kwargs) # generate texture containing the desired label self.label = CoreLabel(text=str(num), font_size=500, color=(1,1,1,1)) self.label.refresh() self.texture_size = list(self.label.texture.size) self.label_texture = self.label.texture pass def animate(self): # animate widget size_old = self.texture_size size_new = (size_old[0] * 1.5, size_old[1] * 1.5) pos = self.pos anim = Animation(size=size_new, pos=(pos[0] - (size_new[0] - size_old[0])/2, pos[1] - (size_new[1] - size_old[1])/2), duration=0.5) #anim = Animation(scale=1.5, pos=(pos[0] - (size_new[0] - size_old[0])/2, pos[1] - (size_new[1] - size_old[1])/2), duration=0.25) anim.start(self) pass
def _calculate_optimum_font_size(self): #cw = self._calculate_widths() words = list(self._iterate_words()) text = ' '.join([x.text for x in words]) font_size = WORD_FONTSIZE corelabel = CoreLabel(text=text, font_name=words[0].font_name) padding = words[0].padding * len(words) # too many words ? if padding > self.width / 2: padding = int(self.width / 2 / len(words)) for word in words: word.padding = padding else: for word in words: word.padding = Word.padding.defaultvalue while True: corelabel.options['font_size'] = sp(font_size) w, h = corelabel.render() if w < self.width - padding: break font_size -= 1 font_size = sp(font_size) if font_size != words[0].font_size: for word in words: word.font_size = font_size word.texture_update()
def update_layout(self): if not self._corelabel: # create new label corelabel = CoreLabel(text=self.text, font_size=self.font_size, color=self.font_color) corelabel.refresh(); self._corelabel = corelabel labeltexture = self._corelabel.texture self.canvas.add(Rectangle(texture=labeltexture, size=(self.width, self.height)))
def build_canvas(self, dt): # get 3 textures curdir = dirname(__file__) arrow_left = CoreImage(join(curdir, 'arrow_left.png')).texture arrow_middle = CoreImage(join(curdir, 'arrow_middle.png')).texture arrow_right = CoreImage(join(curdir, 'arrow_right.png')).texture self.canvas.before.clear() with self.canvas.before: cmax = ((self.date_end - self.date_start) / float(self.date_step)) x, y = self.pos w, h = self.size fh = 100 bh = 10 cy = y + h / 2 h = fh * 2 r = range(self.date_start, self.date_end, self.date_step) for index, cx in enumerate(r): alpha = (cx - self.date_start) / (float(self.date_end) - float(self.date_start)) # create background of arrow (part of) c = 0.9 - (0.4 * alpha) a = 1.0 - 0.4 * alpha Color(c, c, c, a) if index == 0: texture = arrow_left border = (2, 2, 2, 8) elif index == len(r) - 1: texture = arrow_right border = (2, 126, 2, 2) else: texture = arrow_middle border = (2, 0, 2, 0) BorderImage(pos=(x, cy - fh), size=(w/cmax, h), texture=texture, border=border) # create lines x = int(x) if index > 0: Color(1, 1, 1, .8) Line(points=[x, cy - fh - bh, x, cy + fh + bh]) # create label (333f43) label = CoreLabel(text=str(cx), font_size=14, font_name='fonts/DroidSans.ttf') label.refresh() Color(0x33/255., 0x3f/255., 0x43/255.) # trick to invert the label orientation tc = label.texture.tex_coords th, tw = label.texture.size tc = tc[-2:] + tc[0:-2] Rectangle(pos=(x + 5, cy - th / 2), size=(tw, th), texture=label.texture, tex_coords=tc) x += w / cmax
def set_caption(t): print(t.content.text) mylabel = CoreLabel(text=t.content.text, font_size=25, color=self.color, position=(touch.x, touch.y)) # Force refresh to compute things and generate the texture mylabel.refresh() texture = mylabel.texture texture_size = list(texture.size) with self.canvas: self.history.append(Rectangle(pos=(touch.x, touch.y), texture=texture, size=texture_size))
def update_label(self): '''update buttons text''' if self.label == None: # create new label label = CoreLabel(text=self.get_text(), font_size=12, color=(0, 0, 1)) label.refresh(); self.label = label labeltexture= self.label.texture labelsize = list(labeltexture.size)
def render(self): self.rect = Rectangle(size=self.size, pos=self.pos) self.canvas.add(self.rect) label = CoreLabel(text="Text Lable here", font_size=20) label.refresh() text = label.texture #self.canvas.add(Color(self.colour, 1-self.colour,0, 1)) pos = [150,150]#self.pos[i] + (self.size[i] - text.size[i]) / 2 for i in range(2)) self.canvas.add(Rectangle(size=text.size, pos=pos, texture=text)) self.canvas.ask_update()
def draw_step(self, x, y, c): self.canvas.add(Color(c[0], c[1], c[2])) self.canvas.add(Ellipse(pos = [self.cx[x] - self.d/2, self.cy[y] - self.d/2], size = [self.d, self.d])) self.canvas.add(Color(0., 0., 0.)) self.canvas.add(Line(circle = (self.cx[x], self.cy[y], self.d/2))) label = CoreLabel(text="{0}".format(self.app.qsteps), font_size=14) label.refresh() text = label.texture self.canvas.add(Color(1 - c[0], 1- c[1], 1- c[2])) self.canvas.add(Rectangle(size=text.size, pos = [self.cx[x] - text.size[0]/2, self.cy[y] - text.size[1]/2], texture=text))
def draw_text(wid, pos_x, pos_y, font_size, text): pos_y = invert_y(wid, pos_y) label = CoreLabel(text=text, font_size=font_size) label.refresh() texture = label.texture Color(1, 1, 1) Rectangle(pos=(pos_x, pos_y - texture.size[1]/2), size=texture.size) Color(0, 0, 0) Rectangle(texture=texture, pos=(pos_x, pos_y - texture.size[1]/2), size=texture.size)
def _create_line_label(self, text): # Create a label from a text, using line options ntext = text.replace("\n", "").replace("\t", " " * self.tab_width) kw = self._get_line_options() cid = "%s\0%s" % (ntext, str(kw)) texture = Cache.get("textinput.label", cid) if not texture: label = Label(text=ntext, **kw) label.refresh() texture = label.texture Cache.append("textinput.label", cid, texture) return texture
def _create_line_label(self, text): # Create a label from a text, using line options ntext = text.replace('\n', '').replace('\t', ' ' * self.tab_width) kw = self._get_line_options() cid = '%s\0%s' % (ntext, str(kw)) texture = Cache.get('textinput.label', cid) if not texture: label = Label(text=ntext, **kw) label.refresh() texture = label.texture Cache.append('textinput.label', cid, texture) return texture
def _get_texture_pos(self, tick, index, succinct=True, which='time', texture=None): tl = self.tickline # tick_info should be (x, y, width, height) of tick tick_info = self.registrar[tick][index] if not texture: label_kw = tick.get_label_texture(index, succinct, return_kw=True) if not label_kw: return label_kw['font_size'] = self.time_font_size if which == 'time' else \ self.date_font_size label_kw['halign'] = 'left' if tl.is_vertical() else 'center' label = CoreLabel(**label_kw) label.refresh() texture = label.texture if tl.is_vertical(): y = tick_info[1] + tick_info[3] / 2 - texture.height / 2 if which == 'time': dist = self.time_dist_from_edge else: dist = self.date_dist_from_edge dist = max(dist, tick.tick_size[1] + tl.tick_label_padding) halign = tick.halign if halign == 'left': x = tl.x + dist elif halign == 'line_left': x = tl.line_pos - dist - texture.width elif halign == 'line_right': x = tl.line_pos + dist else: x = tl.right - dist - texture.width else: # TODO horizontal is gonna get crowded with text x = tick_info[0] + tick_info[2] / 2 - texture.width / 2 if which == 'time': dist = self.time_dist_from_edge else: dist = self.date_dist_from_edge dist = max(dist, tick.tick_size[1] + tl.tick_label_padding) valign = tick.valign if valign == 'top': y = tl.top - dist - texture.height elif valign == 'line_top': y = tl.line_pos + dist elif valign == 'line_bottom': y = tl.line_pos - dist - texture.height else: y = tl.y + dist return (texture, [x, y])
def _create_label(self): # create the core label class according to markup value if self._label is not None: cls = self._label.__class__ else: cls = None markup = self.markup if (markup and cls is not CoreMarkupLabel) or (not markup and cls is not CoreLabel): # markup have change, we need to change our rendering method. d = Label._font_properties dkw = dict(list(zip(d, [getattr(self, x) for x in d]))) if markup: self._label = CoreMarkupLabel(**dkw) else: self._label = CoreLabel(**dkw)
def on_start(self): """ This is the start point of the kivy ui """ win = Window win.bind(size=self.on_size, on_keyboard=self.on_keyboard) win.bind(on_key_down=self.on_key_down) # Register fonts without this you won't be able to use bold/italic... # inside markup. from kivy.core.text import Label Label.register( "Roboto", "data/fonts/Roboto.ttf", "data/fonts/Roboto.ttf", "data/fonts/Roboto-Bold.ttf", "data/fonts/Roboto-Bold.ttf", ) if platform == "android": # bind to keyboard height so we can get the window contents to # behave the way we want when the keyboard appears. win.bind(keyboard_height=self.on_keyboard_height) self.on_size(win, win.size) config = self.electrum_config storage = WalletStorage(config.get_wallet_path()) Logger.info("Electrum: Check for existing wallet") if storage.file_exists: wallet = Wallet(storage) action = wallet.get_action() else: action = "new" if action is not None: # start installation wizard Logger.debug("Electrum: Wallet not found. Launching install wizard") wizard = Factory.InstallWizard(config, self.network, storage) wizard.bind(on_wizard_complete=self.on_wizard_complete) wizard.run(action) else: wallet.start_threads(self.network) self.on_wizard_complete(None, wallet) self.on_resume()
def __init__(self, labelString, pos=(0, 0), size=((Window.width - 6 * 10) // 5, Window.height // 3)): super(Card, self).__init__() self.pos = pos self.size = size self.color = Color(*self.backColor, mode='rgba') self.outline = Rectangle(pos=pos, size=size) self.rect = Rectangle(pos=pos, size=size) label = CoreLabel(text=labelString, font_size=62) label.refresh() self.rect.texture = label.texture self.add(self.color) self.add(self.outline) self.add(Color(*(0, 0, 0))) self.add(self.rect)
def __init__(self, **kwargs): super(TestApp, self).__init__(**kwargs) Window.bind(on_key_down=self.onKeyDown) Window.bind(on_touch_down=self.onTouch) #TOUCH CAPABILITY self.touch_count = 0 #TOUCH CAPABILITY DEBUGGING COUNTER self.touch_count_label = CoreLabel( text='', font_size=15) #TOUCH CAPABILITY DEBUGGING COUNTER self.key_label = CoreLabel(text='', font_size=15) self.hud = HUD(self.canvas) self.gps_status_label = CoreLabel(text='', font_size=12) self.gps_location_label = CoreLabel(text='', font_size=12) self.uid_label = CoreLabel(text='UID: ', font_size=12) self.my_lat = 0 self.my_lon = 0 self.my_heading = 0 self.my_accuracy = 0 self.DEBUG = True
def plot_weight(cls, dates_exces, axes_offset, axes_size): weight_instr = InstructionGroup() if len(dates_exces) != 0: distance_between_centers = axes_size[0] / len(dates_exces) else: distance_between_centers = 0 max_weight = 0 for d, ex in dates_exces: # move to sep function weight = ex.description.get("value") try: weight = float(weight) except (ValueError, TypeError): weight = 0 if weight > max_weight: max_weight = weight if max_weight != 0: y_distance = axes_size[1] / (max_weight + 1) else: y_distance = 0 for i, (d, ex) in enumerate(dates_exces): weight = ex.description.get("value") try: weight = float(weight) except (ValueError, TypeError): weight = 0 y_pos_top = axes_offset[1] + weight * y_distance y_pos_bottom = axes_offset[1] x_center_pos = axes_offset[0] + distance_between_centers * (i + 1) x_size = 10 y_size = y_pos_top - y_pos_bottom weight_instr.add( Line(points=[ x_center_pos - 5, y_pos_top, x_center_pos + 5, y_pos_top ], width=3)) text_label = CoreLabel(text=str(weight), font_size=15) text_label.refresh() texture = text_label.texture texture_size = list(texture.size) weight_instr.add( Rectangle(texture=texture, size=texture_size, pos=(x_center_pos - 10, y_pos_bottom + (y_pos_top - y_pos_bottom) / 2))) return weight_instr
def __init__(self, capteur, **kvargs): super().__init__(**kvargs) self.g = [] self.L = 300 self.H = 200 self.graphX = [] self.graphY = [] self.y_mid = self.H / 2 self.capteur = capteur self.titre = self.capteur.nom self.label_titre = Label(text=self.titre, color=(1, 0.5, 0), text_size=(self.width, self.height), size_hint=(1, 2), padding_y=0) self.add_widget(self.label_titre) Clock.schedule_interval(self.update, FREQ) self.temps = 0 pas = int(300 / 10 * FREQ) # pas = 3 self.max_graph = int(10 / FREQ) # max_graph = 90 if self.capteur.nom == "Altitude": self.graphY = [0] * self.max_graph for i in range(0, self.max_graph): self.graphX.append(pas * i) else: self.graphY = [self.y_mid] * self.max_graph for i in range(0, self.max_graph): self.graphX.append(pas * i) self.N = 0 for i in range(0, 10): mylabel = CoreLabel(text=str(i - 9), font_size=15, color=(1, 1, 1, 1)) # Force refresh to compute things and generate the texture mylabel.refresh() # Get the texture and the texture size texture = mylabel.texture texture_size = list(texture.size) self.g.append( Rectangle(pos=(17 + i * 30, 100), texture=texture, size=texture_size))
def on_start(self): ''' This is the start point of the kivy ui ''' Logger.info("dpi: {} {}".format(metrics.dpi, metrics.dpi_rounded)) win = Window win.bind(size=self.on_size, on_keyboard=self.on_keyboard) win.bind(on_key_down=self.on_key_down) # Register fonts without this you won't be able to use bold/italic... # inside markup. from kivy.core.text import Label Label.register('Roboto', 'data/fonts/Roboto.ttf', 'data/fonts/Roboto.ttf', 'data/fonts/Roboto-Bold.ttf', 'data/fonts/Roboto-Bold.ttf') if platform == 'android': # bind to keyboard height so we can get the window contents to # behave the way we want when the keyboard appears. win.bind(keyboard_height=self.on_keyboard_height) self.on_size(win, win.size) config = self.electrum_config storage = WalletStorage(config.get_wallet_path()) Logger.info('Electrum: Check for existing wallet') if storage.file_exists: wallet = Wallet(storage) action = wallet.get_action() else: action = 'new' if action is not None: # start installation wizard Logger.debug('Electrum: Wallet not found. Launching install wizard') wizard = Factory.InstallWizard(config, self.network, storage) wizard.bind(on_wizard_complete=self.on_wizard_complete) wizard.run(action) else: wallet.start_threads(self.network) self.on_wizard_complete(None, wallet) self.on_resume()
def update_rect(self, *args): self.ids.libreDrawing.canvas.before.clear() middle = (self.ids.libreDrawing.center_x, self.ids.libreDrawing.center_y) xOffset = middle[0] - self.diametre / 2 + ( self.offset[0] + self.curOffest[0]) * self.zoomFactor yOffset = middle[1] - self.diametre / 2 + ( self.offset[1] + self.curOffest[1]) * self.zoomFactor with self.ids.libreDrawing.canvas.before: Color(1, 0, 0, 1) Ellipse(pos=(xOffset, yOffset), size=(self.diametre, self.diametre)) Color(0, 1, 0, 0.7) points = self.points.copy() for p in points: dist = sum(self.points[p]) / len(self.points[p]) point = (math.cos(p) * dist, math.sin(p) * dist) Ellipse(pos=(xOffset + point[0] * self.zoomFactor, yOffset + point[1] * self.zoomFactor), size=(self.diametre, self.diametre)) if self.lastAngle != None: text = "Distance: " + str( round((sum(self.points[self.lastAngle]) / len(self.points[self.lastAngle])) * 10) / 10) Color(0.5, 0.5, 0.5, .6) Rectangle(pos=(self.size[0] - 200, self.size[1] - (70 + 50)), size=(200, 70)) label = CoreLabel(text=text, font_size=30, halign='left', valign='top', padding=(5, 5)) label.refresh() text = label.texture Color(1, 1, 1, 1) Rectangle(pos=(self.size[0] - 200, self.size[1] - (70 + 50)), size=(200, 70), texture=text)
class CircularProgressBar(ProgressBar): def __init__(self, **kwargs): super(CircularProgressBar, self).__init__(**kwargs) self.thickness = 40 self.label = CoreLabel(text="0", font_size=self.thickness) self.texture_size = None self.refresh_text() self.draw() def draw(self): with self.canvas: self.canvas.clear() #No progress Color(0.26, 0.26, 0.26) Ellipse(pos=self.pos, size=self.size) #Progress Circle Color(1, 0, 0) Ellipse(pos=self.pos, size=self.size, angle_end=(self.value / 100.0) * 360) #will be replaced with necessary data #Inner Circle Color(0, 0, 0) Ellipse(pos=(self.pos[0] + self.thickness / 2, self.pos[1] + self.thickness / 2), size=(self.size[0] - self.thickness, self.size[1] - self.thickness)) #Inner text Color(1, 1, 1, 1) Rectangle(texture=self.label.texture, size=self.texture_size, pos=(self.size[0] / 2 - self.texture_size[0] / 2, self.size[1] / 2 - self.texture_size[1] / 2)) self.label.text = str(int(self.value)) def refresh_text(self): self.label.refresh() self.texture_size = list(self.label.texture.size) def set_value(self, value): self.value = value self.label.text = str(int(self.value)) self.refresh_text() self.draw()
def draw_ticks(self): scangle= self.angle_stop-self.angle_start inc= scangle / ((self.scale_max-self.scale_min)/self.scale_increment) inc /= self.tic_frequency cnt= 0 # create an instruction group so we can remove it and recall draw_ticks to update when pos or size changes self.ticks = InstructionGroup() self.ticks.add(Color(*self.tic_color)) labi = self.scale_min x= -180.0+self.angle_start+self.angle_offset # start while x <= self.angle_stop-180+self.angle_offset : a= x if(x < 0.0) else x+360.0 need_label= True ticlen= self.tic_length if(cnt % self.tic_frequency != 0): ticlen= self.tic_length/2 need_label= False cnt += 1 self.ticks.add(PushMatrix()) self.ticks.add(Rotate(angle=a, axis=(0,0,-1), origin=(self.dial_center[0], self.dial_center[1]))) self.ticks.add(Translate(0, self.tic_radius-ticlen)) self.ticks.add(Line(points=[self.dial_center[0], self.dial_center[1], self.dial_center[0], self.dial_center[1]+ticlen], width=self.tic_width, cap='none', joint='none')) if need_label: #print("label: " + str(labi)) #kw['font_size'] = self.tic_length * 2 label = CoreLabel(text=str(int(round(labi))), font_size=self.scale_font_size) label.refresh() texture= label.texture self.ticks.add(Translate(-texture.size[0]/2, -texture.size[1]-2)) self.ticks.add(Rectangle(texture=texture, pos=self.dial_center, size=texture.size)) labi += self.scale_increment self.ticks.add(PopMatrix()) x += inc self.canvas.add(self.ticks)
def loadstory(self): with open(join(dirname(__file__), 'data', 'story.txt'), 'r') as fd: story = fd.read().split('|') self.words = words = [] cue_Rachel = [] cue_tears = [] spacing_x = 0 wordnumber = 0 # first, prebuilt all the characters texture. # one optimization would be, at the end, to put all the letter into a # big atlas = one texture used letters = '' for eachword in story: if eachword[:1] == '^': continue letters += eachword letters = list(set(letters)) for letter in letters: clabel = CoreLabel(text=letter, font_size=sp(40), font_name=self.font_name) clabel.refresh() self.tex_letters[letter] = clabel.texture for eachword in story: if eachword == "^n": spacing_x += 50 #I really need the width of 27 spaces. Might have to create a sample Word just to do this. elif eachword == "^r": cue_Rachel.append(len(words)) elif eachword == "^t": cue_tears.append(len(words)) else: paragraph_width = self.get_paragraph_width(eachword) words.append({ 'text': eachword, 'width': paragraph_width, 'offset_x': spacing_x }) spacing_x += paragraph_width wordnumber += 1
def __init__(self, num, **kwargs): super(CounterNum, self).__init__(**kwargs) # generate texture containing the desired label self.label = CoreLabel(text=str(num), font_size=500, color=(1,1,1,1)) self.label.refresh() self.texture_size = list(self.label.texture.size) self.label_texture = self.label.texture pass
def get_text_width_height_descent(self, s, prop, ismath): '''This method is needed specifically to calculate text positioning in the canvas. Matplotlib needs the size to calculate the points according to their layout ''' if ismath: ftimage, depth = self.mathtext_parser.parse(s, self.dpi, prop) w = ftimage.get_width() h = ftimage.get_height() return w, h, depth font = resource_find(prop.get_name() + ".ttf") if font is None: plot_text = CoreLabel(font_size=prop.get_size_in_points()) else: plot_text = CoreLabel(font_size=prop.get_size_in_points(), font_name=prop.get_name()) plot_text.text = six.text_type("{}".format(s)) plot_text.refresh() return plot_text.texture.size[0], plot_text.texture.size[1], 1
def spawn_text(self, text, position, size=0.1, orientation="y", color=(1, 1, 1, 1)): my_label = CoreLabel(font_size=int(200 * size)) my_label.text = text my_label.refresh() aspect = float(my_label.texture.size[0]) / my_label.texture.size[1] quad = Quad(Material(map=my_label.texture, color=color[:3], transparency=color[3]), size * aspect, size, orientation=orientation) quad.label = my_label self.spawn(quad, position)
def draw_flags(self, gp_beat: guitarpro.models.Beat, xpos: float): # Texture created by mscore-20 font is unnecessarily tall, hard to place exactly. flags = { 1: '', 2: '', 4: '', 8: u'\uE194', 16: u'\uE197', 32: u'\uE198' } flag = flags[gp_beat.duration.value] flag_glyph = CoreLabel(text=flag, font_size=32, font_name='./fonts/mscore-20') flag_glyph.refresh() flag_instr = Rectangle(pos=(xpos, self.y - self.step_y * 1.5), size=flag_glyph.texture.size) flag_instr.texture = flag_glyph.texture self.glyphs.add(flag_instr)
def _create_label(self): # create the core label class according to markup value if self._label is not None: cls = self._label.__class__ else: cls = None markup = self.markup if (markup and cls is not CoreMarkupLabel) or \ (not markup and cls is not CoreLabel): # markup have change, we need to change our rendering method. d = Label._font_properties dkw = dict(zip(d, [getattr(self, x) for x in d])) # XXX font_size core provider compatibility if Label.font_size.get_format(self) == 'px': dkw['font_size'] *= 1.333 if markup: self._label = CoreMarkupLabel(**dkw) else: self._label = CoreLabel(**dkw)
def FindPath(self): global current_loc current_loc = [(60,30), 0, (-1,-1), (-1,-1)] print(items_to_buy) item_pick_up = items_to_buy.copy() flag = 0 print('removed') if self.dot_path == []: pass else: for dots in self.dot_path: self.canvas.remove(dots) print('removed') self.dot_path = [] while item_pick_up != []: if item_pick_up == []: path = astar.find_path(self.img,current_loc[0],addresses['check_out'][0]) current_loc = addresses['check_out'] flag = 1 near_item = 'check_out' else: near_item = find_nearest(current_loc[0],item_pick_up) path= self.get_path(current_loc,addresses[near_item]) item_pick_up.remove(near_item) current_loc = addresses[near_item] #self.canvas.clear() mylabel = CoreLabel(text=near_item, font_size=10, color=(1, 0, 0, 1)) mylabel.refresh() # Get the texture and the texture size texture = mylabel.texture texture_size = list(texture.size) with self.canvas: Color(1.0,0,0) for i in range(len(path)): self.dot_path.append(Ellipse(pos = ((path[i][1] * 540 / 64) - 133,((64 - path[i][0]) * 540 / 64) - 6 ), size=(3, 3))) #(x - 133,y) Color(0,1,0) self.dot_path.append(Ellipse(pos = ((path[-1][1] * 540 / 64) - 133,((64 - path[-1][0]) * 540 / 64) - 6 ), size=(5, 5))) #(self.canvas.add(Rectangle(pos = ((path[-1][1] * 540 / 64) - 133 - texture.size[0] / 2,((64 - path[-1][0]) * 540 / 64) - 6 + 10), texture=texture, size=texture_size))) #self.add_widget(Label(text = near_item, pos = (7 + (path[-1][1] * 540 / 64) - 133,((64 - path[-1][0]) * 540 / 64) - 6 ))) if flag: break
def __init__(self): super().__init__() #Keyboard controls self._keyboard = Window.request_keyboard(self.on_keyboard, self) self._keyboard.bind(on_key_down=self.on_keyboard_down) self._keyboard.bind(on_key_up=self.on_keyboard_up) #Frame tracker self.register_event_type("on_frame") Clock.schedule_interval(self._on_frame, 0) #spawn rates self.spawn_white_count = 0 self.spawn_fast_count = 0 self.spawn_thick_count = 0 self.spawn_total_count = 0 self.spawn_white_total = 9 self.spawn_fast_total = 2 self.spawn_thick_total = 2 Clock.schedule_interval(self.spawn_normal_enemies, 5) Clock.schedule_interval(self.spawn_fast_enemies, 20) Clock.schedule_interval(self.spawn_thick_enemies, 15) self.keysPressed = set() self._entities = set() #Decoration for score and health tracking self._score_board = Corelabel(text='Reward: $0', font_size=30) self._score_board.refresh() self._score = 0 self._health_board = Corelabel(text='Health =>', font_size=30) self._health_board.refresh() with self.canvas: self._score_instruction = Rectangle( texture=self._score_board.texture, pos=(0, Window.height - 50), size=self._score_board.size) self._health_instruction = Rectangle( texture=self._health_board.texture, pos=(Window.width - 185, Window.height - 55), size=self._health_board.size)
def setUpCanvas(self): self.tb_size = (50, 20) self.instruction_group = InstructionGroup(group=self.get_unique_id()) self.trans_line_color = Color(.9, .9, .9) self.trans_bezier = Line(cap='round', joint='round', width=2, bezier_precision=75) self.trans_arrow_color = Color(.5, .5, .5) self.trans_arrow = Triangle() self.trans_label_bg_color = Color(.6, .6, .6, 1) self.trans_label_bg = Rectangle(size=self.tb_size) self.trans_label_highlight_color = Color(.9, .9, .9) self.trans_label_highlight = Line(cap='round', joint='round', width=1.5) self.trans_label = Label(text_size=self.tb_size, halign='center', valign='middle') self.trans_label.text = str(self.direction) + ': ' + str( self.read_sym) + ', ' + str(self.write_sym) self.trans_label.refresh() self.trans_label_color = Color(1, 1, 1, 1) self.trans_label_rect = Rectangle(size=self.tb_size, texture=self.trans_label.texture) self.instruction_group.add(self.trans_line_color) self.instruction_group.add(self.trans_bezier) self.instruction_group.add(self.trans_arrow_color) self.instruction_group.add(self.trans_arrow) self.instruction_group.add(self.trans_label_bg_color) self.instruction_group.add(self.trans_label_bg) self.instruction_group.add(self.trans_label_highlight_color) self.instruction_group.add(self.trans_label_highlight) self.instruction_group.add(self.trans_label_color) self.instruction_group.add(self.trans_label_rect) self.update_positions()
def draw_rest(self, gp_beat: guitarpro.models.Beat, xpos: float): # The only font I can find for rests doesn't follow the unicode standard. step_y = self.step_y unicode_rests = { 1: u'\u1D13B', 2: u'\u1D13C', 4: u'\u1D13D', 8: u'\u1D13E', 16: u'\u1D13F' } rests = { 1: u'\uE102', 2: u'\uE103', 4: u'\uE107', 8: u'\uE109', 16: u'\uE10A', 32: u'\uE10B' } rest_ys = { 1: step_y * 4, 2: step_y * 3, 4: step_y * 2.5, 8: step_y * 3, 16: step_y * 3, 32: step_y * 2.5 } rest, rest_y = rests[gp_beat.duration.value], rest_ys[ gp_beat.duration.value] rest_glyph = CoreLabel(text=rest, font_size=32, font_name='./fonts/mscore-20') rest_glyph.refresh() rest_instr = Rectangle(pos=(xpos, self.y + rest_y), size=rest_glyph.texture.size) rest_instr.texture = rest_glyph.texture background = Rectangle(pos=(xpos, self.y + rest_y), size=rest_glyph.texture.size) # self.backgrounds.add(background) # Looks bad because of mscore-20 font. self.glyphs.add(rest_instr) if gp_beat.duration.isDotted or gp_beat.duration.isDoubleDotted: ypos = rest_y + rest_glyph.texture.height * 0.75 self.draw_dots(gp_beat, xpos, ypos)
def draw_tuplet(self, gp_beat: guitarpro.models.Beat, xmids: List[float]): xmin, xmax = xmids[0], xmids[-1] for xpos in xmids: self.draw_stem(gp_beat, xpos) if gp_beat.duration.value == 8: self.draw_eightnote_beam(xmin, xmax) if gp_beat.duration.value == 16: self.draw_eightnote_beam(xmin, xmax) self.draw_sixteenthnote_beam(xmin, xmax) xmid = (xmin + xmax) / 2 text_glyph = CoreLabel(text=str(gp_beat.duration.tuplet.enters), font_size=14, font_name='./fonts/Arial') text_glyph.refresh() text_instr = Rectangle(pos=(xmid - text_glyph.texture.width / 2, self.y + self.step_y * 0.5), size=text_glyph.texture.size) text_instr.texture = text_glyph.texture self.glyphs.add(text_instr)
def _create_label(self): # create the core label class according to markup value if self._label is not None: cls = self._label.__class__ else: cls = None markup = self.markup if (markup and cls is not CoreMarkupLabel) or \ (not markup and cls is not CoreLabel): # markup have change, we need to change our rendering method. dkw = {x: getattr(self, x) for x in self._font_properties} dkw['usersize'] = self.text_size if self.disabled: dkw['color'] = self.disabled_color dkw['outline_color'] = self.disabled_outline_color if markup: self._label = CoreMarkupLabel(**dkw) else: self._label = CoreLabel(**dkw)
def __init__(self, **kwargs): super(CircularProgressBar, self).__init__(**kwargs) # Set constant for the bar thickness self._thickness = 8 self._cap_style = "round" self._cap_precision = 10 # Create a direct text representation self._text_label = CoreLabel(text="0", font_size=25, halign="center")
def Message( self, pos, msg=' is a heavy item, hence \nits planned to be \npicked up towards the \nend of the shopping trip' ): size = (225, 90) with self.canvas: self.msg_components.append( Rectangle(source='Message.png', pos=(pos[0] - size[0] / 2, pos[1]), size=size)) mylabel = CoreLabel(text=msg, font_size=13, color=(1, 0, 0, 1)) mylabel.refresh() texture = mylabel.texture texture_size = list(texture.size) self.msg_components.append( Rectangle(pos=(pos[0] - texture_size[0] / 2, pos[1] + 15), texture=texture, size=texture_size)) Clock.schedule_once(self.remove_popup, 5)
def update(self, dt): with self.canvas: for entity, m in self.entity_manager.pairs_for_type(AiguillageY): # Couleur du texte rgba if m.actif: Color(0, 1, 0) else: Color(1, 1, 0) if not float(m.x).is_integer(): s = str(round(m.x, 3)) else: s = "{0}/{1}".format(m.x, m.xout) my_label = CoreLabel(text=m.nom + '\n' + s, font_size=14) # the label is usually not drawn until needed, so force it to draw. my_label.refresh() # Now access the texture of the label and use it wherever x_texture = my_label.texture b = self.entity_manager.component_for_entity( entity, simulation.graphe.Box) Rectangle(size=x_texture.size, pos=b.ptxt, texture=x_texture)
def loadstory(self): with open(join(dirname(__file__), 'data', 'story.txt'), 'r') as fd: story = fd.read().split('|') self.words = words = [] cue_Rachel = [] cue_tears = [] spacing_x = 0 wordnumber = 0 # first, prebuilt all the characters texture. # one optimization would be, at the end, to put all the letter into a # big atlas = one texture used letters = '' for eachword in story: if eachword[:1] == '^': continue letters += eachword letters = list(set(letters)) for letter in letters: clabel = CoreLabel(text=letter, font_size=sp(40), font_name=self.font_name) clabel.refresh() self.tex_letters[letter] = clabel.texture for eachword in story: if eachword == "^n": spacing_x += 50 #I really need the width of 27 spaces. Might have to create a sample Word just to do this. elif eachword == "^r": cue_Rachel.append(len(words)) elif eachword == "^t": cue_tears.append(len(words)) else: paragraph_width = self.get_paragraph_width(eachword) words.append({ 'text': eachword, 'width': paragraph_width, 'offset_x': spacing_x}) spacing_x += paragraph_width wordnumber += 1
def start_cursor(self, x, y): tx, ty = self.transform_to_wpos(x, y) label = CoreLabel(text="{:1.2f},{:1.2f}".format(tx, ty)) label.refresh() texture = label.texture px, py = (x, y) with self.ids.surface.canvas.after: Color(0, 0, 1, mode='rgb', group='cursor_group') self.crossx = [ Rectangle(pos=(px, 0), size=(1, self.height), group='cursor_group'), Rectangle(pos=(0, py), size=(self.width, 1), group='cursor_group'), Line(circle=(px, py, 20), group='cursor_group'), Rectangle(texture=texture, pos=(px - texture.size[0] / 2, py - 40), size=texture.size, group='cursor_group') ]
def draw(self): with self.canvas: line_kwargs = { 'points': [], 'width': 1, } self.color = Color(rgba=(1, 0, 0, 1.)) self.time_lines = [ Line(**line_kwargs) for i in range(self.TIME_INTERVAL_COUNT + 1) ] self.hours_core_labels = [] self.hours_rect_labels = [] for hour in range(24 + 1): label = CoreLabel() label.text = "%02d" % hour label.refresh() self.hours_core_labels.append(label) self.hours_rect_labels.append( Rectangle(size=label.size, texture=label.texture))
def bar_name(self, value: str): if not isinstance(value, str): raise TypeError("Label must a string, not {}!".format(type(value))) else: value = Label(text=value, halign='middle', valign='middle', font_size=20) self._name = value self._name_text = value.text self._name.refresh() self._name_size = value.texture.size
def __init__(self, num, **kwargs): super(CounterNum, self).__init__(**kwargs) # generate texture containing the desired label self.label = CoreLabel(text=str(num), font_size=500, color=(1, 1, 1, 1)) self.label.refresh() self.texture_size = list(self.label.texture.size) self.label_texture = self.label.texture pass
def dowork(self, workIndex): root = BoxLayout(orientation='vertical') self.popup = Popup( title='Life, the Universe, and Everything. There is an answer.', content=root, auto_dismiss=False) if workIndex == 1: content = Label( text= 'Take a long break: \n\n Hectoe9000 is cleaning and drying himself. \nThis will take some time.' ) self.popup.bind(on_open=self.clean) if workIndex == 2: content = Label( text= 'Take a break: \n\n Hectoe9000 is drying. \nThis will take some time.' ) self.popup.bind(on_open=self.dry) root.add_widget(content) self.popup.open()
def get_font_list(): '''Get a list of all the fonts available on this system. ''' CoreLabel._fonts_dirs.append(FONTS_DIR) fonts_path = CoreLabel.get_system_fonts_dir() flist = [] resource_add_path(FONTS_DIR) for fdir in fonts_path: for fpath in sorted(os.listdir(fdir)): if fpath.endswith('.ttf'): flist.append(fpath[:-4]) return sorted(flist)
def float_text_atlas( atlas, canvas, text, pos, timelines, halign ) : label_kargs= {} for k in ( u'font_name', u'font_size', u'padding_x', u'padding_y', ) : cfg= timelines.get( k, None ) if cfg : timeline= cfg[0] if timeline : label_kargs[k]= timeline[0][1] label= CoreLabel( text= text, **label_kargs ) label.refresh() label_width, label_height= label.texture.size ret= atlas.insert( label_width, label_height, None ) if ret : dx, dy= ret else : dx, dy= 0, 0 if halign == u'right' : dx= -dx pos= ( pos[0] + dx, pos[1] + dy ) return float_text( canvas, label, pos, timelines, halign )
def get_font_list(self): '''Get a list of all the fonts available on this system. ''' fonts_path = CoreLabel.get_system_fonts_dir() flist = [] for fdir in fonts_path: for fpath in sorted(os.listdir(fdir)): if fpath.endswith('.ttf'): flist.append(fpath[:-4]) return sorted(flist)
def get_label_texture(self, index, **kw): text = self.value_str(self.slot_value(index)) label = CoreLabel(text=text, font_size=self.font_size, **kw) label.refresh() if label.width > self.width: label = CoreLabel(text=text, font_size=self.width * self.font_size / label.width) label.refresh() return label.texture
class VectorWidget(Widget): label = ObjectProperty() title = StringProperty() length = NumericProperty(10.0) angle = NumericProperty() mode = StringProperty('object') color = ListProperty([1, 1, 1, 1]) scale = NumericProperty(1.0) _scale = NumericProperty(8.5) arrow_size = NumericProperty(4.0) def __init__(self, **kwargs): self.label = Label(text='v', font_size=sp(14), padding=sp(3), valign='middle', halign='center') self.label.refresh() super(VectorWidget, self).__init__(**kwargs) def on_title(self, *largs): self.label.text = self.title self.label.refresh() def on_scale(self, *largs): self._scale = self.scale * 10.0
def get_font_list(self): '''Get a list of all the fonts available on this system. ''' fonts_path = CoreLabel.get_system_fonts_dir() flist = [] for fdir in fonts_path: for fpath in sorted(os.listdir(fdir)): if not '.' in fpath: continue font, ext = fpath.rsplit('.') if ext == 'ttf': flist.append(font) return sorted(flist)
def __init__(self, **kwargs): super(Label, self).__init__(**kwargs) # bind all the property for recreating the texture d = ('text', 'font_size', 'font_name', 'bold', 'italic', 'halign', 'valign', 'padding_x', 'padding_y', 'text_size') dkw = {} for x in d: dkw[x] = curry(self._trigger_texture_update, x) self.bind(**dkw) dkw = dict(zip(d, [getattr(self, x) for x in d])) self._label = CoreLabel(**dkw) # force the texture creation self.texture_update()
def __init__(self, **kwargs): self._trigger_texture = Clock.create_trigger(self.texture_update, -1) super(Label, self).__init__(**kwargs) # bind all the property for recreating the texture d = ('text', 'font_size', 'font_name', 'bold', 'italic', 'halign', 'valign', 'padding_x', 'padding_y', 'text_size', 'shorten', 'mipmap') dkw = {} for x in d: dkw[x] = partial(self._trigger_texture_update, x) self.bind(**dkw) dkw = dict(zip(d, [getattr(self, x) for x in d])) font_name = resource_find(self.font_name) if font_name: dkw['font_name'] = font_name self._label = CoreLabel(**dkw) # force the texture creation self.texture_update()
class Label(Widget): '''Label class, see module documentation for more information. :Events: `on_ref_press` Fired when the user clicks on a word referenced with a ``[ref]`` tag in a text markup. ''' _font_properties = ('text', 'font_size', 'font_name', 'bold', 'italic', 'halign', 'valign', 'padding_x', 'padding_y', 'text_size', 'shorten', 'mipmap', 'markup', 'line_height', 'max_lines') def __init__(self, **kwargs): self._trigger_texture = Clock.create_trigger(self.texture_update, -1) self.register_event_type('on_ref_press') super(Label, self).__init__(**kwargs) # bind all the property for recreating the texture d = Label._font_properties dkw = {} for x in d: dkw[x] = partial(self._trigger_texture_update, x) self.bind(**dkw) self._label = None self._create_label() # force the texture creation self._trigger_texture() def _create_label(self): # create the core label class according to markup value if self._label is not None: cls = self._label.__class__ else: cls = None markup = self.markup if (markup and cls is not CoreMarkupLabel) or \ (not markup and cls is not CoreLabel): # markup have change, we need to change our rendering method. d = Label._font_properties dkw = dict(list(zip(d, [getattr(self, x) for x in d]))) if markup: self._label = CoreMarkupLabel(**dkw) else: self._label = CoreLabel(**dkw) def _trigger_texture_update(self, name=None, source=None, value=None): # check if the label core class need to be switch to a new one if name == 'markup': self._create_label() if source: if name == 'text': self._label.text = value elif name == 'text_size': self._label.usersize = value elif name == 'font_size': self._label.options[name] = value else: self._label.options[name] = value self._trigger_texture() def texture_update(self, *largs): '''Force texture recreation with the current Label properties. After this function call, the :data:`texture` and :data:`texture_size` will be updated in this order. ''' self.texture = None if self._label.text.strip() == '': self.texture_size = (0, 0) else: mrkup = self._label.__class__ is CoreMarkupLabel if mrkup: text = self._label.text self._label.text = ''.join(('[color=', get_hex_from_color(self.color), ']', text, '[/color]')) self._label.refresh() # force the rendering to get the references if self._label.texture: self._label.texture.bind() self._label.text = text self.refs = self._label.refs self.anchors = self._label.anchors else: self._label.refresh() texture = self._label.texture if texture is not None: self.texture = self._label.texture self.texture_size = list(self.texture.size) def on_touch_down(self, touch): if super(Label, self).on_touch_down(touch): return True if not len(self.refs): return False tx, ty = touch.pos tx -= self.center_x - self.texture_size[0] / 2. ty -= self.center_y - self.texture_size[1] / 2. ty = self.texture_size[1] - ty for uid, zones in self.refs.items(): for zone in zones: x, y, w, h = zone if x <= tx <= w and y <= ty <= h: self.dispatch('on_ref_press', uid) return True return False def on_ref_press(self, ref): pass # # Properties # disabled_color = ListProperty([1, 1, 1, .3]) '''Text color, in the format (r, g, b, a) .. versionadded:: 1.8.0 :data:`disabled_color` is a :class:`~kivy.properties.ListProperty` and defaults to [1, 1, 1, .5]. ''' text = StringProperty('') '''Text of the label. Creation of a simple hello world:: widget = Label(text='Hello world') If you want to create the widget with an unicode string, use:: widget = Label(text=u'My unicode string') :data:`text` is a :class:`~kivy.properties.StringProperty` and defaults to ''. ''' text_size = ListProperty([None, None]) '''By default, the label is not constrained to any bounding box. You can set the size constraint of the label with this property. .. versionadded:: 1.0.4 For example, whatever your current widget size is, if you want the label to be created in a box with width=200 and unlimited height:: Label(text='Very big big line', text_size=(200, None)) .. note:: This text_size property is the same as the :data:`~kivy.core.text.Label.usersize` property in the :class:`~kivy.core.text.Label` class. (It is named size= in the constructor.) :data:`text_size` is a :class:`~kivy.properties.ListProperty` and defaults to (None, None), meaning no size restriction by default. ''' font_name = StringProperty('DroidSans') '''Filename of the font to use. The path can be absolute or relative. Relative paths are resolved by the :func:`~kivy.resources.resource_find` function. .. warning:: Depending of your text provider, the font file can be ignored. However, you can mostly use this without problems. If the font used lacks the glyphs for the particular language/symbols you are using, you will see '[]' blank box characters instead of the actual glyphs. The solution is to use a font that has the glyphs you need to display. For example, to display |unicodechar|, use a font such as freesans.ttf that has the glyph. .. |unicodechar| image:: images/unicode-char.png :data:`font_name` is a :class:`~kivy.properties.StringProperty` and defaults to 'DroidSans'. ''' font_size = NumericProperty('15sp') '''Font size of the text, in pixels. :data:`font_size` is a :class:`~kivy.properties.NumericProperty` and defaults to 12dp. ''' line_height = NumericProperty(1.0) '''Line Height for the text. e.g. line_height = 2 will cause the spacing between lines to be twice the size. :data:`line_height` is a :class:`~kivy.properties.NumericProperty` and defaults to 1.0. .. versionadded:: 1.5.0 ''' bold = BooleanProperty(False) '''Indicates use of the bold version of your font. .. note:: Depending of your font, the bold attribute may have no impact on your text rendering. :data:`bold` is a :class:`~kivy.properties.BooleanProperty` and defaults to False. ''' italic = BooleanProperty(False) '''Indicates use of the italic version of your font. .. note:: Depending of your font, the italic attribute may have no impact on your text rendering. :data:`italic` is a :class:`~kivy.properties.BooleanProperty` and defaults to False. ''' padding_x = NumericProperty(0) '''Horizontal padding of the text inside the widget box. :data:`padding_x` is a :class:`~kivy.properties.NumericProperty` and defaults to 0. ''' padding_y = NumericProperty(0) '''Vertical padding of the text inside the widget box. :data:`padding_x` is a :class:`~kivy.properties.NumericProperty` and defaults to 0. ''' padding = ReferenceListProperty(padding_x, padding_y) '''Padding of the text in the format (padding_x, padding_y) :data:`padding` is a :class:`~kivy.properties.ReferenceListProperty` of (:data:`padding_x`, :data:`padding_y`) properties. ''' halign = OptionProperty('left', options=['left', 'center', 'right', 'justify']) '''Horizontal alignment of the text. :data:`halign` is an :class:`~kivy.properties.OptionProperty` and defaults to 'left'. Available options are : left, center, right and justified. .. warning:: This doesn't change the position of the text texture of the Label (centered), only the position of the text in this texture. You probably want to bind the size of the Label to the :data:`texture_size` or set a :data:`text_size`. .. versionchanged:: 1.6.0 A new option was added to :data:`halign`, namely `justify`. ''' valign = OptionProperty('bottom', options=['bottom', 'middle', 'top']) '''Vertical alignment of the text. :data:`valign` is an :class:`~kivy.properties.OptionProperty` and defaults to 'bottom'. Available options are : bottom, middle and top. .. warning:: This doesn't change the position of the text texture of the Label (centered), only the position of the text within this texture. You probably want to bind the size of the Label to the :data:`texture_size` or set a :data:`text_size` to change this behavior. ''' color = ListProperty([1, 1, 1, 1]) '''Text color, in the format (r, g, b, a) :data:`color` is a :class:`~kivy.properties.ListProperty` and defaults to [1, 1, 1, 1]. ''' texture = ObjectProperty(None, allownone=True) '''Texture object of the text. The text is rendered automatically when a property changes. The OpenGL texture created in this operation is stored in this property. You can use this :data:`texture` for any graphics elements. Depending on the texture creation, the value will be a :class:`~kivy.graphics.texture.Texture` or :class:`~kivy.graphics.texture.TextureRegion` object. .. warning:: The :data:`texture` update is scheduled for the next frame. If you need the texture immediately after changing a property, you have to call the :meth:`texture_update` method before accessing :data:`texture`:: l = Label(text='Hello world') # l.texture is good l.font_size = '50sp' # l.texture is not updated yet l.texture_update() # l.texture is good now. :data:`texture` is an :class:`~kivy.properties.ObjectProperty` and defaults to None. ''' texture_size = ListProperty([0, 0]) '''Texture size of the text. .. warning:: The :data:`texture_size` is set after the :data:`texture` property. If you listen for changes to :data:`texture`, :data:`texture_size` will not be up-to-date in your callback. Bind to :data:`texture_size` instead. ''' mipmap = BooleanProperty(False) '''Indicates whether OpenGL mipmapping is applied to the texture or not. Read :ref:`mipmap` for more information. .. versionadded:: 1.0.7 :data:`mipmap` is a :class:`~kivy.properties.BooleanProperty` and defaults to False. ''' shorten = BooleanProperty(False) ''' Indicates whether the label should attempt to shorten its textual contents as much as possible if a `text_size` is given. Setting this to True without an appropriately set `text_size` will lead to unexpected results. :data:`shorten` is a :class:`~kivy.properties.BooleanProperty` and defaults to False. ''' markup = BooleanProperty(False) ''' .. versionadded:: 1.1.0 If True, the text will be rendered using the :class:`~kivy.core.text.markup.MarkupLabel`: you can change the style of the text using tags. Check the :doc:`api-kivy.core.text.markup` documentation for more information. :data:`markup` is a :class:`~kivy.properties.BooleanProperty` and defaults to False. ''' refs = DictProperty({}) ''' .. versionadded:: 1.1.0 List of ``[ref=xxx]`` markup items in the text with the bounding box of all the words contained in a ref, available only after rendering. For example, if you wrote:: Check out my [ref=hello]link[/hello] The refs will be set with:: {'hello': ((64, 0, 78, 16), )} You know that the reference "hello" has a bounding box at (x1, y1, x2, y2). The current Label implementation uses these references if they exist in your markup text, automatically doing the collision with the touch and dispatching an `on_ref_press` event. You can bind a ref event like this:: def print_it(instance, value): print('User click on', value) widget = Label(text='Hello [ref=world]World[/ref]', markup=True) widget.on_ref_press(print_it) .. note:: This works only with markup text. You need :data:`markup` set to True. ''' anchors = DictProperty({}) ''' .. versionadded:: 1.1.0 Position of all the ``[anchor=xxx]`` markup in the text. You can place anchors in your markup text as follows:: text = """ [anchor=title1][size=24]This is my Big title.[/size] [anchor=content]Hello world """ Then, all the ``[anchor=]`` references will be removed and you'll get all the anchor positions in this property (only after rendering):: >>> widget = Label(text=text, markup=True) >>> widget.texture_update() >>> widget.anchors {"content": (20, 32), "title1": (20, 16)} .. note:: This works only with markup text. You need :data:`markup` set to True. ''' max_lines = NumericProperty(0) '''Maximum number of lines to use, defaults to 0, which means unlimited.
def test_unicode_name(self): from kivy.core.text import Label lbl = Label(font_name=self.font_name) lbl.refresh() self.assertNotEqual(lbl.get_extents(''), None)
class Label(Widget): """Label class, see module documentation for more information. :Events: `on_ref_press` Fired when the user clicks on a word referenced with a ``[ref]`` tag in a text markup. """ __events__ = ["on_ref_press"] _font_properties = ( "text", "font_size", "font_name", "bold", "italic", "underline", "strikethrough", "color", "disabled_color", "halign", "valign", "padding_x", "padding_y", "text_size", "shorten", "mipmap", "markup", "line_height", "max_lines", "strip", "shorten_from", "split_str", "unicode_errors", "font_hinting", "font_kerning", "font_blended", ) def __init__(self, **kwargs): self._trigger_texture = Clock.create_trigger(self.texture_update, -1) super(Label, self).__init__(**kwargs) # bind all the property for recreating the texture d = Label._font_properties fbind = self.fbind update = self._trigger_texture_update fbind("disabled", update, "disabled") for x in d: fbind(x, update, x) self._label = None self._create_label() # force the texture creation self._trigger_texture() def _create_label(self): # create the core label class according to markup value if self._label is not None: cls = self._label.__class__ else: cls = None markup = self.markup if (markup and cls is not CoreMarkupLabel) or (not markup and cls is not CoreLabel): # markup have change, we need to change our rendering method. d = Label._font_properties dkw = dict(list(zip(d, [getattr(self, x) for x in d]))) if markup: self._label = CoreMarkupLabel(**dkw) else: self._label = CoreLabel(**dkw) def _trigger_texture_update(self, name=None, source=None, value=None): # check if the label core class need to be switch to a new one if name == "markup": self._create_label() if source: if name == "text": self._label.text = value elif name == "text_size": self._label.usersize = value elif name == "font_size": self._label.options[name] = value elif name == "disabled_color" and self.disabled: self._label.options["color"] = value elif name == "disabled": self._label.options["color"] = self.disabled_color if value else self.color else: self._label.options[name] = value self._trigger_texture() def texture_update(self, *largs): """Force texture recreation with the current Label properties. After this function call, the :attr:`texture` and :attr:`texture_size` will be updated in this order. """ mrkup = self._label.__class__ is CoreMarkupLabel self.texture = None if not self._label.text or (self.halign == "justify" or self.strip) and not self._label.text.strip(): self.texture_size = (0, 0) if mrkup: self.refs, self._label._refs = {}, {} self.anchors, self._label._anchors = {}, {} else: if mrkup: text = self.text # we must strip here, otherwise, if the last line is empty, # markup will retain the last empty line since it only strips # line by line within markup if self.halign == "justify" or self.strip: text = text.strip() self._label.text = "".join( ( "[color=", get_hex_from_color(self.disabled_color if self.disabled else self.color), "]", text, "[/color]", ) ) self._label.refresh() # force the rendering to get the references if self._label.texture: self._label.texture.bind() self.refs = self._label.refs self.anchors = self._label.anchors else: self._label.refresh() texture = self._label.texture if texture is not None: self.texture = self._label.texture self.texture_size = list(self.texture.size) def on_touch_down(self, touch): if super(Label, self).on_touch_down(touch): return True if not len(self.refs): return False tx, ty = touch.pos tx -= self.center_x - self.texture_size[0] / 2.0 ty -= self.center_y - self.texture_size[1] / 2.0 ty = self.texture_size[1] - ty for uid, zones in self.refs.items(): for zone in zones: x, y, w, h = zone if x <= tx <= w and y <= ty <= h: self.dispatch("on_ref_press", uid) return True return False def on_ref_press(self, ref): pass # # Properties # disabled_color = ListProperty([1, 1, 1, 0.3]) """Text color, in the format (r, g, b, a) .. versionadded:: 1.8.0 :attr:`disabled_color` is a :class:`~kivy.properties.ListProperty` and defaults to [1, 1, 1, .5]. """ text = StringProperty("") """Text of the label. Creation of a simple hello world:: widget = Label(text='Hello world') If you want to create the widget with an unicode string, use:: widget = Label(text=u'My unicode string') :attr:`text` is a :class:`~kivy.properties.StringProperty` and defaults to ''. """ text_size = ListProperty([None, None]) """By default, the label is not constrained to any bounding box. You can set the size constraint of the label with this property. The text will autoflow into the constrains. So although the font size will not be reduced, the text will be arranged to fit into the box as best as possible, with any text still outside the box clipped. This sets and clips :attr:`texture_size` to text_size if not None. .. versionadded:: 1.0.4 For example, whatever your current widget size is, if you want the label to be created in a box with width=200 and unlimited height:: Label(text='Very big big line', text_size=(200, None)) .. note:: This text_size property is the same as the :attr:`~kivy.core.text.Label.usersize` property in the :class:`~kivy.core.text.Label` class. (It is named size= in the constructor.) :attr:`text_size` is a :class:`~kivy.properties.ListProperty` and defaults to (None, None), meaning no size restriction by default. """ font_name = StringProperty("Roboto") """Filename of the font to use. The path can be absolute or relative. Relative paths are resolved by the :func:`~kivy.resources.resource_find` function. .. warning:: Depending of your text provider, the font file can be ignored. However, you can mostly use this without problems. If the font used lacks the glyphs for the particular language/symbols you are using, you will see '[]' blank box characters instead of the actual glyphs. The solution is to use a font that has the glyphs you need to display. For example, to display |unicodechar|, use a font such as freesans.ttf that has the glyph. .. |unicodechar| image:: images/unicode-char.png :attr:`font_name` is a :class:`~kivy.properties.StringProperty` and defaults to 'Roboto'. """ font_size = NumericProperty("15sp") """Font size of the text, in pixels. :attr:`font_size` is a :class:`~kivy.properties.NumericProperty` and defaults to 15sp. """ line_height = NumericProperty(1.0) """Line Height for the text. e.g. line_height = 2 will cause the spacing between lines to be twice the size. :attr:`line_height` is a :class:`~kivy.properties.NumericProperty` and defaults to 1.0. .. versionadded:: 1.5.0 """ bold = BooleanProperty(False) """Indicates use of the bold version of your font. .. note:: Depending of your font, the bold attribute may have no impact on your text rendering. :attr:`bold` is a :class:`~kivy.properties.BooleanProperty` and defaults to False. """ italic = BooleanProperty(False) """Indicates use of the italic version of your font. .. note:: Depending of your font, the italic attribute may have no impact on your text rendering. :attr:`italic` is a :class:`~kivy.properties.BooleanProperty` and defaults to False. """ underline = BooleanProperty(False) """Adds an underline to the text. .. note:: This feature requires the SDL2 text provider. .. versionadded:: 1.9.2 :attr:`underline` is a :class:`~kivy.properties.BooleanProperty` and defaults to False. """ strikethrough = BooleanProperty(False) """Adds a strikethrough line to the text. .. note:: This feature requires the SDL2 text provider. .. versionadded:: 1.9.2 :attr:`strikethrough` is a :class:`~kivy.properties.BooleanProperty` and defaults to False. """ padding_x = NumericProperty(0) """Horizontal padding of the text inside the widget box. :attr:`padding_x` is a :class:`~kivy.properties.NumericProperty` and defaults to 0. .. versionchanged:: 1.9.0 `padding_x` has been fixed to work as expected. In the past, the text was padded by the negative of its values. """ padding_y = NumericProperty(0) """Vertical padding of the text inside the widget box. :attr:`padding_y` is a :class:`~kivy.properties.NumericProperty` and defaults to 0. .. versionchanged:: 1.9.0 `padding_y` has been fixed to work as expected. In the past, the text was padded by the negative of its values. """ padding = ReferenceListProperty(padding_x, padding_y) """Padding of the text in the format (padding_x, padding_y) :attr:`padding` is a :class:`~kivy.properties.ReferenceListProperty` of (:attr:`padding_x`, :attr:`padding_y`) properties. """ halign = OptionProperty("left", options=["left", "center", "right", "justify"]) """Horizontal alignment of the text. :attr:`halign` is an :class:`~kivy.properties.OptionProperty` and defaults to 'left'. Available options are : left, center, right and justify. .. warning:: This doesn't change the position of the text texture of the Label (centered), only the position of the text in this texture. You probably want to bind the size of the Label to the :attr:`texture_size` or set a :attr:`text_size`. .. versionchanged:: 1.6.0 A new option was added to :attr:`halign`, namely `justify`. """ valign = OptionProperty("bottom", options=["bottom", "middle", "center", "top"]) """Vertical alignment of the text. :attr:`valign` is an :class:`~kivy.properties.OptionProperty` and defaults to 'bottom'. Available options are : `'bottom'`, `'middle'` (or `'center'`) and `'top'`. .. versionchanged:: 1.9.2 The `'center'` option has been added as an alias of `'middle'`. .. warning:: This doesn't change the position of the text texture of the Label (centered), only the position of the text within this texture. You probably want to bind the size of the Label to the :attr:`texture_size` or set a :attr:`text_size` to change this behavior. """ color = ListProperty([1, 1, 1, 1]) """Text color, in the format (r, g, b, a) :attr:`color` is a :class:`~kivy.properties.ListProperty` and defaults to [1, 1, 1, 1]. """ texture = ObjectProperty(None, allownone=True) """Texture object of the text. The text is rendered automatically when a property changes. The OpenGL texture created in this operation is stored in this property. You can use this :attr:`texture` for any graphics elements. Depending on the texture creation, the value will be a :class:`~kivy.graphics.texture.Texture` or :class:`~kivy.graphics.texture.TextureRegion` object. .. warning:: The :attr:`texture` update is scheduled for the next frame. If you need the texture immediately after changing a property, you have to call the :meth:`texture_update` method before accessing :attr:`texture`:: l = Label(text='Hello world') # l.texture is good l.font_size = '50sp' # l.texture is not updated yet l.texture_update() # l.texture is good now. :attr:`texture` is an :class:`~kivy.properties.ObjectProperty` and defaults to None. """ texture_size = ListProperty([0, 0]) """Texture size of the text. The size is determined by the font size and text. If :attr:`text_size` is [None, None], the texture will be the size required to fit the text, otherwise it's clipped to fit :attr:`text_size`. When :attr:`text_size` is [None, None], one can bind to texture_size and rescale it proportionally to fit the size of the label in order to make the text fit maximally in the label. .. warning:: The :attr:`texture_size` is set after the :attr:`texture` property. If you listen for changes to :attr:`texture`, :attr:`texture_size` will not be up-to-date in your callback. Bind to :attr:`texture_size` instead. """ mipmap = BooleanProperty(False) """Indicates whether OpenGL mipmapping is applied to the texture or not. Read :ref:`mipmap` for more information. .. versionadded:: 1.0.7 :attr:`mipmap` is a :class:`~kivy.properties.BooleanProperty` and defaults to False. """ shorten = BooleanProperty(False) """ Indicates whether the label should attempt to shorten its textual contents as much as possible if a :attr:`text_size` is given. Setting this to True without an appropriately set :attr:`text_size` will lead to unexpected results. :attr:`shorten_from` and :attr:`split_str` control the direction from which the :attr:`text` is split, as well as where in the :attr:`text` we are allowed to split. :attr:`shorten` is a :class:`~kivy.properties.BooleanProperty` and defaults to False. """ shorten_from = OptionProperty("center", options=["left", "center", "right"]) """The side from which we should shorten the text from, can be left, right, or center. For example, if left, the ellipsis will appear towards the left side and we will display as much text starting from the right as possible. Similar to :attr:`shorten`, this option only applies when :attr:`text_size` [0] is not None, In this case, the string is shortened to fit within the specified width. .. versionadded:: 1.9.0 :attr:`shorten_from` is a :class:`~kivy.properties.OptionProperty` and defaults to `center`. """ split_str = StringProperty("") """The string used to split the :attr:`text` while shortening the string when :attr:`shorten` is True. For example, if it's a space, the string will be broken into words and as many whole words that can fit into a single line will be displayed. If :attr:`shorten_from` is the empty string, `''`, we split on every character fitting as much text as possible into the line. .. versionadded:: 1.9.0 :attr:`split_str` is a :class:`~kivy.properties.StringProperty` and defaults to `''` (the empty string). """ unicode_errors = OptionProperty("replace", options=("strict", "replace", "ignore")) """How to handle unicode decode errors. Can be `'strict'`, `'replace'` or `'ignore'`. .. versionadded:: 1.9.0 :attr:`unicode_errors` is an :class:`~kivy.properties.OptionProperty` and defaults to `'replace'`. """ markup = BooleanProperty(False) """ .. versionadded:: 1.1.0 If True, the text will be rendered using the :class:`~kivy.core.text.markup.MarkupLabel`: you can change the style of the text using tags. Check the :doc:`api-kivy.core.text.markup` documentation for more information. :attr:`markup` is a :class:`~kivy.properties.BooleanProperty` and defaults to False. """ refs = DictProperty({}) """ .. versionadded:: 1.1.0 List of ``[ref=xxx]`` markup items in the text with the bounding box of all the words contained in a ref, available only after rendering. For example, if you wrote:: Check out my [ref=hello]link[/ref] The refs will be set with:: {'hello': ((64, 0, 78, 16), )} The references marked "hello" have a bounding box at (x1, y1, x2, y2). These co-ordinates are relative to the top left corner of the text, with the y value increasing downwards. You can define multiple refs with the same name: each occurence will be added as another (x1, y1, x2, y2) tuple to this list. The current Label implementation uses these references if they exist in your markup text, automatically doing the collision with the touch and dispatching an `on_ref_press` event. You can bind a ref event like this:: def print_it(instance, value): print('User click on', value) widget = Label(text='Hello [ref=world]World[/ref]', markup=True) widget.on_ref_press(print_it) .. note:: This works only with markup text. You need :attr:`markup` set to True. """ anchors = DictProperty({}) ''' .. versionadded:: 1.1.0 Position of all the ``[anchor=xxx]`` markup in the text. These co-ordinates are relative to the top left corner of the text, with the y value increasing downwards. Anchors names should be unique and only the first occurence of any duplicate anchors will be recorded. You can place anchors in your markup text as follows:: text = """ [anchor=title1][size=24]This is my Big title.[/size] [anchor=content]Hello world """ Then, all the ``[anchor=]`` references will be removed and you'll get all the anchor positions in this property (only after rendering):: >>> widget = Label(text=text, markup=True) >>> widget.texture_update() >>> widget.anchors {"content": (20, 32), "title1": (20, 16)} .. note:: This works only with markup text. You need :attr:`markup` set to True. ''' max_lines = NumericProperty(0) """Maximum number of lines to use, defaults to 0, which means unlimited. Please note that :attr:`shorten` take over this property. (with shorten, the text is always one line.) .. versionadded:: 1.8.0 :attr:`max_lines` is a :class:`~kivy.properties.NumericProperty` and defaults to 0. """ strip = BooleanProperty(False) """Whether leading and trailing spaces and newlines should be stripped from each displayed line. If True, every line will start at the right or left edge, depending on :attr:`halign`. If :attr:`halign` is `justify` it is implicitly True. .. versionadded:: 1.9.0 :attr:`strip` is a :class:`~kivy.properties.BooleanProperty` and defaults to False. """ font_hinting = OptionProperty("normal", options=[None, "normal", "light", "mono"], allownone=True) """What hinting option to use for font rendering. Can be one of `'normal'`, `'light'`, `'mono'` or None. .. note:: This feature requires the SDL2 text provider. .. versionadded:: 1.9.2 :attr:`font_hinting` is an :class:`~kivy.properties.OptionProperty` and defaults to `'normal'`. """ font_kerning = BooleanProperty(True) """Whether kerning is enabled for font rendering. .. note:: This feature requires the SDL2 text provider. .. versionadded:: 1.9.2 :attr:`font_kerning` is a :class:`~kivy.properties.BooleanProperty` and defaults to True. """ font_blended = BooleanProperty(True) """Whether blended or solid font rendering should be used.
class Label(Widget): '''Label class, see module documentation for more information. ''' def __init__(self, **kwargs): self._trigger_texture = Clock.create_trigger(self.texture_update, -1) super(Label, self).__init__(**kwargs) # bind all the property for recreating the texture d = ('text', 'font_size', 'font_name', 'bold', 'italic', 'halign', 'valign', 'padding_x', 'padding_y', 'text_size', 'shorten', 'mipmap') dkw = {} for x in d: dkw[x] = partial(self._trigger_texture_update, x) self.bind(**dkw) dkw = dict(zip(d, [getattr(self, x) for x in d])) font_name = resource_find(self.font_name) if font_name: dkw['font_name'] = font_name self._label = CoreLabel(**dkw) # force the texture creation self.texture_update() def _trigger_texture_update(self, name=None, source=None, value=None): if source: if name == 'text': self._label.text = value elif name == 'text_size': self._label.usersize = value elif name == 'font_name': rvalue = resource_find(value) self._label.options['font_name'] = rvalue if rvalue else value else: self._label.options[name] = value self._trigger_texture() def texture_update(self, *largs): '''Force texture recreation with the current Label properties. After this function call, the :data:`texture` and :data`texture_size` will be updated in this order. ''' self.texture = None if self._label.text.strip() == '': self.texture_size = (0, 0) else: self._label.refresh() texture = self._label.texture if texture is not None: self.texture = self._label.texture self.texture_size = list(self.texture.size) # # Properties # text = StringProperty('') '''Text of the label. Creation of a simple hello world :: widget = Label(text='Hello world') If you want to create the widget with an unicode string, use :: widget = Label(text=u'My unicode string') :data:`text` a :class:`~kivy.properties.StringProperty`. ''' text_size = ListProperty([None, None]) '''By default, the label is not constrained to any bounding box. You can set the size constraint of the label with this property. .. versionadded:: 1.0.4 For example, whatever your current widget size is, if you want the label to be created in a box with width=200 and unlimited height:: Label(text='Very big big line', text_size=(200, None)) .. note:: This text_size property is the same as :data:`~kivy.core.text.Label.usersize` property in :class:`~kivy.core.text.Label` class. (Even if it's named size= in constructor.) :data:`text_size` is a :class:`~kivy.properties.ListProperty`, default to (None, None), meaning no size restriction by default. ''' font_name = StringProperty('fonts/DroidSans.ttf') '''Filename of the font to use, the path can be absolute or relative. Relative paths are resolved by the :func:`~kivy.resources.resource_find` function. .. warning:: Depending of your text provider, the font file can be ignored. But you can mostly use this without trouble. :data:`font_name` is a :class:`~kivy.properties.StringProperty`, default to 'fonts/DroidSans.ttf'. ''' font_size = NumericProperty(12) '''Font size of the text, in pixels. :data:`font_size` is a :class:`~kivy.properties.NumericProperty`, default to 12. ''' bold = BooleanProperty(False) '''Indicate if you want to use the bold version of your font. .. note:: Depending of your font, the bold attribute may have no impact on your text rendering. :data:`bold` is a :class:`~kivy.properties.BooleanProperty`, default to False ''' italic = BooleanProperty(False) '''Indicate if you want to use the italic version of your font. .. note:: Depending of your font, the italic attribute may have no impact on your text rendering. :data:`italic` is a :class:`~kivy.properties.BooleanProperty`, default to False ''' padding_x = NumericProperty(0) '''Horizontal padding of the text, inside the widget box. :data:`padding_x` is a :class:`~kivy.properties.NumericProperty`, default to 0 ''' padding_y = NumericProperty(0) '''Vertical padding of the text, inside the widget box. :data:`padding_x` is a :class:`~kivy.properties.NumericProperty`, default to 0 ''' padding = ReferenceListProperty(padding_x, padding_y) '''Padding of the text, in the format (padding_x, padding_y) :data:`padding` is a :class:`~kivy.properties.ReferenceListProperty` of (:data:`padding_x`, :data:`padding_y`) properties. ''' halign = OptionProperty('left', options=['left', 'center', 'right']) '''Horizontal alignment of the text. :data:`halign` is a :class:`~kivy.properties.OptionProperty`, default to 'left'. Available options are : left, center and right. ''' valign = OptionProperty('bottom', options=['bottom', 'middle', 'top']) '''Vertical alignment of the text. :data:`valign` is a :class:`~kivy.properties.OptionProperty`, default to 'bottom'. Available options are : bottom, middle and top. ''' color = ListProperty([1, 1, 1, 1]) '''Text color, in the format (r, g, b, a) :data:`color` is a :class:`~kivy.properties.ListProperty`, default to [1, 1, 1, 1]. ''' texture = ObjectProperty(None, allownone=True) '''Texture object of the text. The text is rendered automatically when a property changes, and stored in this property. You can use this :data:`texture` for any graphics elements. Depending on the texture creation, the value will be a :class:`~kivy.graphics.texture.Texture` or :class:`~kivy.graphics.texture.TextureRegion` object. .. warning:: The :data:`texture` update is scheduled for the next frame. If you need the texture immediately after changing a property, you have to call the :func:`texture_update` function before acessing :data:`texture` :: l = Label(text='Hello world') # l.texture is good l.font_size = 50 # l.texture is not updated yet l.update_texture() # l.texture is good now. :data:`texture` is a :class:`~kivy.properties.ObjectProperty`, default to None. ''' texture_size = ListProperty([0, 0]) '''Texture size of the text. .. warning:: The data:`texture_size` is set after the :data:`texture` property. If you listen for changes to :data:`texture`, :data:`texture_size` will not be up to date in your callback. Bind to data:`texture_size` instead. ''' mipmap = BooleanProperty(False) '''Indicate if you want OpenGL mipmapping applied to texture or not. Read :ref:`mipmap` for more information. .. versionadded:: 1.0.7 :data:`mipmap` is a :class:`~kivy.properties.BooleanProperty`, default to False. ''' shorten = BooleanProperty(False) '''
import os from threading import Thread from windowManager import hide_GUI, save_GUI_window_id reload(sys) sys.setdefaultencoding("utf-8") # set font from kivy.core.text import Label try: os.chdir(os.path.dirname(__file__)) except Exception: pass Label.register("DroidSans", "./Resources/fonts/DroidSansFallbackFull.ttf") Builder.load_string(''' <Main>: pos: 0,0 padding: 50 rows: 6 row_force_default: True row_default_height: 50 spacing: 50 orientation: 'vertical' canvas: Color: rgba: 0.368, 0.384, 0.447, 0.8 Rectangle: