def update(self, dt): with self.canvas: for entity, a in self.entity_manager.pairs_for_type(Accumulateur): # Couleur du texte rgba if a.full(): Color(0.7, 0, 0) # rouge c'est plein elif a.empty(): Color(0, 1, 1) # cyan c'est vide elif a.get() < a.dispo( ): # tout n'est pas dispo (a cause de transit) Color(1, 1, 0) # jaune c'est partiellement dispo else: Color(0, 1, 0) # vert tout est dispo if not float(a.get()).is_integer(): s = str(round(a.get(), 3)) if a.getmax() != Accumulateur.infini: s += "/" + str(round(a.getmax(), 3)) else: s = str(a.get()) if a.getmax() != Accumulateur.infini: s += "/" + str(a.getmax()) my_label = CoreLabel(text=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 li = self.entity_manager.component_for_entity( entity, simulation.graphe.Ligne) Rectangle(size=x_texture.size, pos=li.ptxt, texture=x_texture)
def draw_plot(self, node, color=None, depth=0, angle=0, parent_angle=360): if depth > 2: return None highlighted_node = None for idx, child in enumerate(node.get_children()): segm_color = (idx % len(self.colors)) if color is None else color w, h = self.size child_angle = child.get_size() / \ child.get_size_parent_directory() * parent_angle if child_angle < 2: continue cx = w / 2 cy = h / 2 r = 100 + 50 * depth segment_width = 50 angle_start = angle angle_end = angle + child_angle mouse_in_segment = self.mouse_in_segment(cx, cy, r, segment_width, angle_start, angle_end) if mouse_in_segment: highlighted_node = child self.draw_segment(cx, cy, r, segment_width, angle_start, angle_end, self.colors[segm_color][depth], mouse_in_segment) highlighted_node = self.draw_plot( child, segm_color, depth+1, angle, child_angle) or \ highlighted_node angle += child_angle if highlighted_node and depth == 0: label = CoreLabel(text=highlighted_node.get_name(), font_size=20) label.refresh() text = label.texture Rectangle(size=text.size, pos=(0, 0), texture=text) return highlighted_node
class CircularProgressBar(ProgressBar): def __init__(self, **kwargs): super(CircularProgressBar, self).__init__(**kwargs) # Set constant for the bar thickness self.thickness = 40 # Create a direct text representation self.label = CoreLabel(text="0%", font_size=self.thickness) # Initialise the texture_size variable self.texture_size = None # Refresh the text self.refresh_text() # Redraw on innit self.draw() def draw(self): with self.canvas: # Empty canvas instructions self.canvas.clear() # Draw no-progress circle Color(0.26, 0.26, 0.26) Ellipse(pos=self.pos, size=self.size) # Draw progress circle, small hack if there is no progress (angle_end = 0 results in full progress) Color(1, 0, 0) Ellipse(pos=self.pos, size=self.size, angle_end=(0.001 if self.value_normalized == 0 else self.value_normalized * 360)) # Draw the inner circle (colour should be equal to the background) 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)) # Center and draw the progress 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)) def refresh_text(self): # Render the label self.label.refresh() # Set the texture size each refresh self.texture_size = list(self.label.texture.size) def set_value(self, value): # Update the progress bar value self.value = value # Update textual value and refresh the texture self.label.text = str(int(self.value_normalized * 100)) + "%" self.refresh_text() # Draw all the elements self.draw()
def drawText(self, text, size, x, y, r, g, b, a): label = Label(text=text, font_size=size, color=(r, g, b, a)) label.refresh() texture = label.texture texture_size = list(texture.size) with self.canvas: Rectangle(texture=texture, pos=(x, y), size=texture_size)
def show_solution(self, present): if present is None: self.add_widget( Label(text="No solution", color=(0, 1, 0, 1), size=self.size)) return with self.canvas: Color(0, 0, 0, 1) Rectangle(pos=(0, 0), size=self.size) height = len(present) width = len(present[0]) self.grid_layout.cols = height self.grid_layout.rows = width for x in range(width): for y in range(height): symbol = present[y][x] if symbol != '#': Color(0, 1, 0, 1) text = "" if symbol == "&&" else symbol label = CoreLabel(text=text, font_size=20) label.refresh() coord_x = x * self.CELL_SIZE + self.OFFSET top_offset = (y + 1) * self.CELL_SIZE coord_y = self.height - top_offset + self.OFFSET Rectangle(pos=(coord_x, coord_y), texture=label.texture, size=label.texture.size) self.draw_empty_rectangle(x, self.height - top_offset)
def ticks_instructions(cls, axes_offsets, axes_sizes, dates_exces): x_ticks = InstructionGroup() ticks_len = 5 if len(dates_exces) != 0: x_ticks_distance = axes_sizes[0] / len(dates_exces) else: x_ticks_distance = 0 yyyy_mm_dd = [x.split(' ')[0] for (x, y) in dates_exces] for i, d in enumerate(yyyy_mm_dd): x_ticks.add( Line(points=[ axes_offsets[0] + (i + 1) * x_ticks_distance, axes_offsets[1], axes_offsets[0] + (i + 1) * x_ticks_distance, axes_offsets[1] - ticks_len ], width=3)) text_label = CoreLabel(text=d, font_size=15) text_label.refresh() texture = text_label.texture texture_size = list(texture.size) x_ticks.add( Rectangle(texture=texture, size=texture_size, pos=(axes_offsets[0] + (i + 1) * x_ticks_distance - 45, axes_offsets[1] - ticks_len - 25))) return x_ticks
def annotate_image(self, string): top_text, bot_text = string.split(',') top_label = CoreLabel(text=top_text, font_size=50, text_size=(800, 80), halign='center', valign='top', outline_width=10, outline_color=(50, 50, 50)) bot_label = CoreLabel(text=bot_text, font_size=50, text_size=(800, 80), halign='center', valign='bottom', outline_width=10) top_label.refresh() bot_label.refresh() top_tex = top_label.texture bot_tex = bot_label.texture with self.canvas: Color(0, 0, 0) Rectangle(size=top_tex.size, pos=(0, 400)) Rectangle(size=bot_tex.size, pos=(0, 0)) Color(255, 255, 255) Rectangle(size=top_tex.size, pos=(0, 400), texture=top_tex) Rectangle(size=bot_tex.size, pos=(0, 0), texture=bot_tex) pass
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 draw_text(pos, text, **kw): label = CoreLabel(text=text, bold=True, **kw) label.refresh() Rectangle(texture=label.texture, pos=(pos[0] - label.texture.size[0] / 2, pos[1] - label.texture.size[1] / 2), size=label.texture.size)
def _required_size_for_cells(cells: List[List[AutosizeTableCell]], base_font_size: float) -> Tuple[int, int]: required_width = 0 required_height = 0 label = None last_font_size = -1 for row in cells: row_height = 0 sumw = sum([cell.layout_weight for cell in row]) weight_ratios = [sumw / cell.layout_weight for cell in row] for cell, wrat in zip(row, weight_ratios): fsize = base_font_size * cell.relative_font_size # Updating an existing label's font size doesn't affect its computed # size, so we have to recreate it if the font size changes. if label is None or last_font_size != fsize: debug(f'New label: {fsize}') pad = fsize * cell.relative_padding label = CoreLabel(font_size=fsize, padding=pad) last_font_size = fsize label.text = cell.text label.refresh() size = label.texture.size required_width = max(required_width, size[0] * wrat) row_height = max(row_height, size[1]) required_height += row_height return (required_width, required_height)
def redraw(self, msize=32): cid = core.data.character_id self.canvas.clear() for o in core.data.items.values(): if o["is_dropped"]: self.canvas.add(Color(1,1,0,1)) self.canvas.add(Ellipse(size=(msize, msize), pos=(o["x"]*msize-msize/2, o["y"]*msize-msize/2))) for key, o in core.data.characters.items(): if o["is_dead"]: continue if key == cid: self.canvas.add(Color(1,1,1,1)) else: self.canvas.add(Color(1,0,0,1)) # キャラクターの線画 self.canvas.add(Ellipse(size=(msize, msize), pos=(o["x"]*msize-msize/2, o["y"]*msize-msize/2))) # キャラクターアングルの線画 self.canvas.add(Color(0,0,0,1)) ap = self.angle_pos(o, msize) self.canvas.add(Ellipse(size=(msize*0.2, msize*0.2), pos=(ap[0]-msize*0.1, ap[1]-msize*0.1))) if cid and cid in core.data.characters: self.canvas.add(Color(1,1,1,1)) # render item names for idx,item_id in enumerate(core.data.characters[cid]["items"]): label = Label(text=core.data.items[item_id]["name"], font_size=msize*2) label.refresh() self.canvas.add(Rectangle(size=label.texture.size, pos=(0, idx*msize*2), texture=label.texture)) # render position label = Label(text="{}, {}, {}".format(core.data.characters[cid]["x"], core.data.characters[cid]["y"], core.data.characters[cid]["attack_charge"]), font_size=msize*2) label.refresh() self.canvas.add(Rectangle(size=label.texture.size, pos=(0, WINDOWSIZE[1]-msize*2), texture=label.texture))
def __init__(self, accuracy, pos, second): super(AccuracyDisplay, self).__init__() self.accuracy = accuracy font_size = 25 self.pos = pos self.size = (100, 25) self.box = Rectangle(pos=pos, size=self.size) box_color = Color(0, 0, 0, 0) self.add(box_color) self.add(self.box) label = CoreLabel(text=self.accuracy, font_size=font_size) # the label is usually not drawn until needed, so force it to draw label.refresh() # now access the texture of the label and use it texture = label.texture if accuracy == "Perfect": self.color = Color(0, 1, 0) elif accuracy == "Good": self.color = Color(1, 127 / 255, 80 / 255) elif accuracy == "Miss": self.color = Color(1, 0, 0) self.add(self.color) text_pos = list(self.pos[i] + (self.size[i] - texture.size[i]) / 2 for i in range(2)) self.label = Rectangle(size=texture.size, pos=text_pos, texture=texture) self.add(self.label) max_time = 2 self.alpha_anim = KFAnim((second, 1), (second + max_time, 0)) # color disappears self.set_second(second)
def __init__(self, combo, second): super(ComboDisplay, self).__init__() self.combo = combo font_size = 25 self.pos = [Window.width / 2, Window.height / 2 + 100] self.size = (100, 25) self.box = Rectangle(pos=self.pos, size=self.size) box_color = Color(0, 0, 0, 0) self.add(box_color) self.add(self.box) label = CoreLabel(text='Combo %d' % (self.combo), font_size=font_size) # the label is usually not drawn until needed, so force it to draw label.refresh() # now access the texture of the label and use it texture = label.texture self.color = Color(0, 0, 1) self.add(self.color) text_pos = list(self.pos[i] + (self.size[i] - texture.size[i]) / 2 for i in range(2)) self.label = Rectangle(size=texture.size, pos=text_pos, texture=texture) self.add(self.label) max_time = 1 self.alpha_anim = KFAnim((second, 1), (second + max_time, 0)) # color disappears self.set_second(second)
def btn_left(self, flayout, text_input): if text_input.text != "": str2 = text_input.text float = FloatLayout() float.pos_hint = {'x': 0, 'y': 0} my_label = CoreLabel() my_label.text = str2 my_label.refresh() newsize = my_label.size mybtn = Button(text=str2, size_hint_y=None, size_hint_x=None, size=(newsize[0] + 10, newsize[1] + 10), pos_hint={ 'x': 0, 'y': 0 }) mybtn.font_size = 12 mybtn.font_name = 'Arial' mybtn.border = 0, 0, 0, 0 mybtn.background_normal = 'gr.png' float.add_widget(mybtn) flayout.add_widget(float) text_input.text = ""
def redraw(self): self.canvas.clear() with self.canvas: Color(*COL_FG) total_ticks = int(self.total_axis_space / self.space_btw_marks) for i in range(total_ticks): if i % 5 == 0: # Long Mark mark = self.mark_length else: # Short Mark mark = self.mark_length / 2 Line(points=[ self.fwidth - mark, i * self.space_btw_marks, self.fwidth, i * self.space_btw_marks, self.fwidth, (i + 1) * self.space_btw_marks ]) i = int(self.total_axis_space / self.space_btw_marks) Line(points=[ self.fwidth - self.mark_length, i * self.space_btw_marks, self.fwidth, i * self.space_btw_marks ]) for i in range(int(total_ticks / 5) + 1): label = CoreLabel() label.text = "{:.1f}".format(0.1 * i) label.refresh() label_texture = label.texture texture_size = list(label_texture.size) Rectangle(texture=label_texture, size=[s * 0.9 for s in texture_size], pos=(0, i * 5 * self.space_btw_marks - 2))
def __init__(self, pattern=None, key=None, aggregate=0): super(ScoreViewer, self).__init__(size=(Window.width, Window.height)) self.info = topleft_label() self.add_widget(self.info) self.info.text = 'Press SPACE to shift through bars' self.pattern = pattern self.key = key self.canvas.add(Color(.3, .3, .3)) crect = CRectangle(cpos=(Window.width // 2, Window.height // 2), csize=(Window.width, Window.height)) self.canvas.add(crect) self.canvas.add(Color(1, 1, 1)) self.card = CRectangle(cpos=(Window.width // 2, Window.height // 2), csize=(self.width // 4, self.height // 4)) text = "No Info right now" label = CoreLabel(text, pos=self.card.cpos) label.refresh() self.card.texture = label.texture self.canvas.add(self.card) self.gui = KeyboardGui() self.canvas.add(self.gui) self.player = DataPlayer(callback=self.gui.preview) self.barNum = -1 #self.score_dict = {} self.data = None self.barData = None
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 affiche_timer(self, texte, size, a, b): mylabel = CoreLabel(text=texte, font_size=size, color=(1, 1, 1, 1)) mylabel.refresh() texture = mylabel.texture texture_size = list(texture.size) with self.canvas: Rectangle(pos=(a, b), texture=texture, size=texture_size)
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
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 __init__(self, content, contentSize, color=COLOR["LIGHT"]["MAIN_COLOR"], font_size=20, **kwargs): super(ShortenText, self).__init__(**kwargs) texture = Short(text=content, color=color, text_size=[contentSize[0], None], shorten=True, shorten_from="right", split_str="", font_size=font_size) texture.refresh() if texture.texture.height < contentSize[1]: texture.text_size = texture.texture.size else: texture.text_size = contentSize texture.max_lines = 5 texture.render() texture.refresh() self.texture = Image(texture=texture.texture, pos_hint={ "x": 0, "top": 1 }) self.size_hint = [None, None] self.size = texture.texture.size self.add_widget(self.texture)
def label_size(text: str, font_size: float) -> Tuple[int, int]: label = CoreLabel(text=text, font_size=font_size) label.refresh() r1 = label.texture.size label.text = text + text label.refresh() r2 = label.texture.size return r1 + r2
def get_text_width(text, font, root=None): logging.info("get_text_width: %s %s" % (text, font)) label = CoreLabel() label.text = text label.refresh() return label.content_width
def draw_text(pos, text, font_name=None, **kw): label = CoreLabel(text=text, bold=True, font_name=font_name or i18n.font_name, **kw) # label.refresh() Rectangle( texture=label.texture, pos=(pos[0] - label.texture.size[0] / 2, pos[1] - label.texture.size[1] / 2), size=label.texture.size, )
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
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 get_label_texture(self, index, **kw): if self.invert: index *= -1 label = CoreLabel(text=get_str_date(index, self.strftime) if self.strftime else \ self.rollinglist[self.slot_value(index)] if len(self.rollinglist) else \ self.value_str(self.slot_value(index)), font_size=self.font_size, **kw) label.refresh() return label.texture
def draw_text_on_canvas(arg_text, font_size=12, **kwargs): # get text texture label = CoreLabel(text=arg_text, font_size=font_size) label.refresh() tex = label.texture # draw text return Rectangle(size=tex.size, texture=tex, **kwargs)
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 test_icons_have_size(): from kivymd.icon_definitions import md_icons from kivy.core.text import Label lbl = Label(font_name="Icons") for icon_name, icon_value in md_icons.items(): assert len(icon_value) == 1 lbl.refresh() assert lbl.get_extents(icon_value) is not None
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 plot_sets_reps(cls, dates_exces, axes_offset, axes_size): sets_reps_instr = InstructionGroup() if len(dates_exces) != 0: distance_between_centers = axes_size[0] / len(dates_exces) else: distance_between_centers = 0 max_total = 0 for d, ex in dates_exces: # move to sep function ex_total = 0 reps = ex.description.get("reps") for r in reps: try: ex_total = ex_total + int(r) except ValueError: ex_total = ex_total + 0 if ex_total > max_total: max_total = ex_total if max_total != 0: y_distance = axes_size[1] / (max_total + 1) else: y_distance = 0 for i, (d, ex) in enumerate(dates_exces): sets = ex.description.get("sets") reps = ex.description.get("reps") weights = ex.description.get("weights") int_reps = [] for r in reps: try: int_reps.append(int(r)) except ValueError: int_reps.append(0) for i_r, r in enumerate(int_reps): y_pos_top = axes_offset[1] + \ sum( int_reps[0:i_r+1] ) * y_distance y_pos_bottom = axes_offset[1] + \ sum( int_reps[0:i_r] ) * y_distance x_center_pos = \ axes_offset[0] + distance_between_centers * (i + 1) x_size = 10 y_size = y_pos_top - y_pos_bottom sets_reps_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(r), font_size=15) text_label.refresh() texture = text_label.texture texture_size = list(texture.size) sets_reps_instr.add( Rectangle(texture=texture, size=texture_size, pos=(x_center_pos - 10, y_pos_bottom + (y_pos_top - y_pos_bottom) / 2))) return sets_reps_instr
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 plot_dists_times(cls, dates_exces, axes_offset, axes_size): dists_times_instr = InstructionGroup() if len(dates_exces) != 0: distance_between_centers = axes_size[0] / len(dates_exces) else: distance_between_centers = 0 max_total = 0 for d, ex in dates_exces: # move to sep function ex_total = 0 dists = ex.description.get("distances") for dist in dists: try: ex_total = ex_total + float(dist) except ValueError: ex_total = ex_total + 0 if ex_total > max_total: max_total = ex_total if max_total != 0: y_distance = axes_size[1] / (max_total + 1) else: y_distance = 0 for i, (d, ex) in enumerate(dates_exces): distances = ex.description.get("distances") times = ex.description.get("times") float_dists = [] for dist in distances: try: float_dists.append(float(dist)) except ValueError: float_dists.append(0) for f_d, d in enumerate(float_dists): y_pos_top = axes_offset[1] + \ sum( float_dists[0:f_d+1] ) * y_distance y_pos_bottom = axes_offset[1] + \ sum( float_dists[0:f_d] ) * y_distance x_center_pos = \ axes_offset[0] + distance_between_centers * (i + 1) x_size = 10 y_size = y_pos_top - y_pos_bottom dists_times_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(d), font_size=15) text_label.refresh() texture = text_label.texture texture_size = list(texture.size) dists_times_instr.add( Rectangle(texture=texture, size=texture_size, pos=(x_center_pos - 10, y_pos_bottom + (y_pos_top - y_pos_bottom) / 2))) return dists_times_instr
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_title(self): with self.canvas: # draw TITLE label label = CoreLabel(text=TITLE, font_size=60) label.refresh() text = label.texture pos = ((Window.size[0] - text.size[0]) / 2, (Window.size[1] * 1.85 - text.size[1]) * 0.5) Color(*map(lambda c: c / 255, LINE_COLOR1)) Rectangle(size=text.size, pos=pos, 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 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 _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 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 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 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 _paint_electrodes_data_setup( self, config, electrode_names, spacing=2, draw_size=(0, 0), draw_size_hint=(1, 1), draw_pos=(0, 0), draw_pos_hint=(None, None), volt_scale=1e-6, time_axis_s=1, volt_axis=100, transform_matrix=None, label_width=70): from kivy.graphics import ( Mesh, StencilPush, StencilUse, StencilUnUse, StencilPop, Rectangle, Color) from kivy.graphics.context_instructions import ( PushMatrix, PopMatrix, Scale, MatrixInstruction) from kivy.graphics.transformation import Matrix from kivy.base import EventLoop EventLoop.ensure_window() from kivy.core.text import Label from kivy.metrics import dp, sp n_rows = len(electrode_names) if not n_rows: raise ValueError("There must be at least one electrode specified") n_cols = len(electrode_names[0]) if not n_cols: raise ValueError("There must be at least one electrode specified") if not all((len(row) == n_cols for row in electrode_names)): raise ValueError( "The number of electrodes in all rows must be the same") n_electrodes = sum(map(len, electrode_names)) orig_w, orig_h = config['orig_size'] fbo = config['canvas'] label_height = 45 if label_width else 0 draw_w, draw_h = draw_size draw_hint_w, draw_hint_h = draw_size_hint w = int(draw_w if draw_hint_w is None else orig_w * draw_hint_w) h = int(draw_h if draw_hint_h is None else orig_h * draw_hint_h) draw_x, draw_y = draw_pos draw_hint_x, draw_hint_y = draw_pos_hint x = int(draw_x if draw_hint_x is None else orig_w * draw_hint_x) y = int(draw_y if draw_hint_y is None else orig_h * draw_hint_y) ew = int((w - label_width - max(0, n_cols - 1) * spacing) / n_cols) eh = int((h - label_height - max(0, n_rows - 1) * spacing) / n_rows) with fbo: PushMatrix() # center = x + w / 2., y + h / 2. # if scale: # Scale(scale, scale, 1, origin=center) if transform_matrix is not None: mat = Matrix() mat.set(array=transform_matrix) m = MatrixInstruction() m.matrix = mat positions = [(0, 0), ] * n_electrodes graphics = [None, ] * n_electrodes i = 0 electrode_color = 1, 215 / 255, 0, 1 for row, row_names in enumerate(reversed(electrode_names)): ey = y + label_height if row: ey += (eh + spacing) * row for col, name in enumerate(row_names): if name is None: i += 1 continue ex = x + label_width if col: ex += (ew + spacing) * col positions[i] = ex, ey fbo.add(Color(*electrode_color)) fbo.add(StencilPush()) fbo.add(Rectangle(pos=(ex, ey), size=(ew, eh))) fbo.add(StencilUse()) graphics[i] = Mesh(mode='line_strip') fbo.add(graphics[i]) fbo.add(StencilUnUse()) fbo.add(Rectangle(pos=(ex, ey), size=(ew, eh))) fbo.add(StencilPop()) i += 1 if label_width: if not col: fbo.add(Color(1, 1, 1, 1)) label = Label(text=name, font_size=sp(40)) label.refresh() _w, _h = label.texture.size rect = Rectangle( pos=(x, ey + (eh - _h) / 2.), size=label.texture.size) rect.texture = label.texture fbo.add(rect) if not row: fbo.add(Color(1, 1, 1, 1)) label = Label(text=name, font_size=sp(40)) label.refresh() _w, _h = label.texture.size rect = Rectangle( pos=(ex + (ew - _w) / 2., y), size=label.texture.size) rect.texture = label.texture fbo.add(rect) with fbo: Color(1, 1, 1, 1) PopMatrix() electrodes_data = [None, ] * n_electrodes # y_min, y_max = float('inf'), float('-inf') alignment = np.array(self.electrode_intensity_alignment) # get the frequency from any channel name = None for row_names in electrode_names: for name in row_names: if name is not None: break if name is not None: break freq = self.electrodes_metadata[name]['sampling_frequency'] frame_n = int(1 / config['rate'] * freq) n_t = int(time_axis_s * freq) t_vals = np.arange(n_t) / (n_t - 1) * ew y_scale = (eh / 2) / volt_axis for i, name in enumerate(itertools.chain(*electrode_names)): if name is None: continue offset, scale = self.get_electrode_offset_scale(name) electrodes_data[i] = \ self.electrodes_data[name], offset, scale / volt_scale # y_min = min(np.min(data), y_min) # y_max = max(np.max(data), y_max) new_config = { 'alignment': alignment, 'frame_n': frame_n, 't_vals': t_vals, 'y_scale': y_scale, 'electrodes_data': electrodes_data, 'n_t': n_t, 'positions': positions, 'graphics': graphics, 'eh': eh} return CallableGen(self._paint_electrodes_data(new_config))
def _show_mea_outline(self, config, transform_matrix=None): from kivy.graphics import ( Line, StencilPush, StencilUse, StencilUnUse, StencilPop, Rectangle, Color) from kivy.graphics.context_instructions import ( PushMatrix, PopMatrix, Rotate, Translate, Scale, MatrixInstruction, BindTexture) from kivy.graphics.transformation import Matrix from kivy.base import EventLoop EventLoop.ensure_window() from kivy.core.text import Label from kivy.metrics import dp, sp size = config['orig_size'] pos = config['pos'] canvas = config['canvas'] mea_w = max(self.view_controller.mea_num_cols - 1, 0) * \ self.view_controller.mea_pitch mea_h = max(self.view_controller.mea_num_rows - 1, 0) * \ self.view_controller.mea_pitch last_col = "ABCDEFGHJKLMNOPQRSTUVWXYZ"[ self.view_controller.mea_num_cols - 1] with canvas: StencilPush() Rectangle(pos=pos, size=size) StencilUse() PushMatrix() if transform_matrix is not None: mat = Matrix() mat.set(array=transform_matrix) m = MatrixInstruction() m.matrix = mat Color(1, 215 / 255, 0, .2) Line(points=[0, 0, mea_w, 0, mea_w, mea_h, 0, mea_h], close=True) label = Label(text='A1', font_size=sp(12)) label.refresh() _w, _h = label.texture.size rect = Rectangle( pos=(mea_w, mea_h - _h / 2.), size=label.texture.size) rect.texture = label.texture label = Label( text='A{}'.format(self.view_controller.mea_num_rows), font_size=sp(12)) label.refresh() _w, _h = label.texture.size rect = Rectangle( pos=(-_w, mea_h - _h / 2.), size=label.texture.size) rect.texture = label.texture label = Label(text='{}1'.format(last_col), font_size=sp(12)) label.refresh() _w, _h = label.texture.size rect = Rectangle(pos=(mea_w, -_h / 2.), size=label.texture.size) rect.texture = label.texture label = Label( text='{}{}'.format(last_col, self.view_controller.mea_num_rows), font_size=sp(12)) label.refresh() _w, _h = label.texture.size rect = Rectangle(pos=(-_w, -_h / 2.), size=label.texture.size) rect.texture = label.texture PopMatrix() StencilUnUse() Rectangle(pos=pos, size=size) StencilPop()
class BezierTest(FloatLayout): def __init__(self, points=[], loop=False, *args, **kwargs): super(BezierTest, self).__init__(*args, **kwargs) self.d = 10 # pixel tolerance when clicking on a point self.points = points self.loop = loop self.saved_points=[] self.line_height = 0 self.current_point = None # index of point being dragged self.GA = threading.Thread(target=RunGA, args=(self,)) self.GA.start() print "Spin thread." self.label = CoreLabel(text=LSTM.trade_stocks[0], font_size=20) self.label.refresh() self.label2 = CoreLabel(text=LSTM.trade_stocks[0], font_size=10) self.label2.refresh() self.label3 = CoreLabel(text=LSTM.trade_stocks[0], font_size=10) self.label3.refresh() with self.canvas: Color(1.0, 0.0, 0.0) #self.cb = Callback(self.my_callback) Color(0.1, 0.1, 0.1) seg = 1300/6 Line( points=[75,0,75,800], width=0.8, close=False) Line( points=[seg,0,seg,800], width=0.8, close=False) Line( points=[seg*2,0,seg*2,800], width=0.8, close=False) Line( points=[seg*3,0,seg*3,800], width=0.8, close=False) Line( points=[seg*4,0,seg*4,800], width=0.8, close=False) Line( points=[seg*5,0,seg*5,800], width=0.8, close=False) Line( points=[seg*6,0,seg*6,800], width=0.8, close=False) Line( points=[1335,0,1335,800], width=5, close=False) '''self.bezier = Bezier( points=self.points, segments=150, loop=self.loop, dash_length=100, dash_offset=10) ''' Color(0.0, 0.0, 1.0) self.line1 = Line( points=self.points, width=0.8, close=False) """s = Slider(y=0, pos_hint={'x': .3}, size_hint=(.3, None), height=20) s.bind(value=self._set_bezier_dash_offset) self.add_widget(s) s = Slider(y=20, pos_hint={'x': .3}, size_hint=(.3, None), height=20) s.bind(value=self._set_line_dash_offset) self.add_widget(s)""" def my_callback(self, instr): print('I have been called!') 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 update(self, dt): with self.canvas: self.line_height Color(0.4, 0.4, 0.4) self.line1.points = self.saved_points self.line1 = Line( points=self.saved_points, width=0.8, close=False) Line( points=[0,self.line_height,2500,self.line_height], width=0.5, close=False) Color(.4, 0.4, .4) #self.line1.points = self.saved_points #self.cb.ask_update() #print "redraw line" def draw_point(self, pos, sell): with self.canvas.after: if sell: Color(0.0, 1.0, 0.0) else: Color(0.0, 0.5, 1.0) Line(circle=(pos[0], pos[1], 4), width=1.6) def draw_rect(self, pos, sell, count, count2, umoney, dmoney): with self.canvas: #if sell>0: Color(0.0, 1.0, 0.0) #Rectangle(pos=(pos[0]+count*2, pos[1]+8), size=(2, 10)) Rectangle(pos=(pos[0], pos[1]+8), size=(count, 7)) #Rectangle(pos=(pos[0], pos[1]+20), size=(umoney, 7)) #else: Color(1.0, 0.0, 0.0) #Rectangle(pos=(pos[0]+count*2, pos[1]-13), size=(2, 10)) Rectangle(pos=(pos[0], pos[1]-13), size=(count2, 7)) #Rectangle(pos=(pos[0], pos[1]-21), size=(dmoney, 7)) def draw_text(self, txt, pos, txt_size, color=[.7,.7,.7]): with self.canvas: CoreLabel2(text=str(txt), pos=pos, font_size=txt_size) #Color(1.0, 1.0, 1.0) #text = self.label.texture #pos2 = list(pos[i] + (self.size[i] - text.size[i]) / 2 for i in range(2)) #Rectangle(size=text.size, pos=pos, texture=text) def update_lines(self): #self.line1.points = self.saved_points #with self.canvas: # Color((.8+random.random()*.2)*.5, (.8+random.random()*.2)*.5, (.8+random.random()*.2)*.5) print "updating line" def _set_bezier_dash_offset(self, instance, value): pass # effect to reduce length while increase offset #self.bezier.dash_length = 100 - value #self.bezier.dash_offset = value def _set_line_dash_offset(self, instance, value): pass # effect to reduce length while increase offset #self.line.dash_length = 100 - value #self.line.dash_offset = value def on_touch_down(self, touch): with self.canvas: self.line1.points = self.saved_points if self.collide_point(touch.pos[0], touch.pos[1]): for i, p in enumerate(list(zip(self.points[::2], self.points[1::2]))): if (abs(touch.pos[0] - self.pos[0] - p[0]) < self.d and abs(touch.pos[1] - self.pos[1] - p[1]) < self.d): self.current_point = i + 1 return True return super(BezierTest, self).on_touch_down(touch) def on_touch_up(self, touch): with self.canvas: self.line1.points = self.saved_points if self.collide_point(touch.pos[0], touch.pos[1]): if self.current_point: self.current_point = None return True return super(BezierTest, self).on_touch_up(touch) def on_touch_move(self, touch): if self.collide_point(touch.pos[0], touch.pos[1]): c = self.current_point if c: self.points[(c - 1) * 2] = touch.pos[0] - self.pos[0] self.points[(c - 1) * 2 + 1] = touch.pos[1] - self.pos[1] self.bezier.points = self.points self.line.points = self.points + self.points[:2] return True return super(BezierTest, self).on_touch_move(touch)
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. ''' 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') 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 _trigger_texture_update(self, name=None, source=None, value=None): if source: if name == 'text': self._label.text = value else: self._label.options[name] = value Clock.unschedule(self.texture_update) Clock.schedule_once(self.texture_update) 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._label.refresh() self.texture = 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`. ''' font_name = StringProperty('fonts/DejaVuSans.ttf') '''File of the font to use. The path used for the font can be a absolute path, or a relative path that will be search with 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/DejaVuSans.ttf'. ''' font_size = NumericProperty(10) '''Font size of the text. The font size is in pixels. :data:`font_size` is a :class:`~kivy.properties.NumericProperty`, default to 10. ''' 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 after each properties changes, and stored inside this property. You can use this :data:`texture` for any graphics elements. Depending of the texture creation, the value will be a :class:`~kivy.graphics.texture.Texture` or :class:`~kivy.graphics.texture.TextureRegion` object. .. warning:: The texture update is scheduled for the next frame. That's mean if you really want the texture just after changing a property, you need to call :func:`texture_update` function before :: 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.
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', 'font_family', 'color', 'disabled_color', 'halign', 'valign', 'padding_x', 'padding_y', 'outline_width', 'disabled_outline_color', 'outline_color', 'text_size', 'shorten', 'mipmap', 'line_height', 'max_lines', 'strip', 'shorten_from', 'split_str', 'ellipsis_options', 'unicode_errors', 'markup', 'font_hinting', 'font_kerning', 'font_blended', 'font_context', 'font_features', 'base_direction', 'text_language') 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_outline_color' and self.disabled: self._label.options['outline_color'] = value elif name == 'disabled': self._label.options['color'] = self.disabled_color if value \ else self.color self._label.options['outline_color'] = ( self.disabled_outline_color if value else self.outline_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) self.is_shortened = False 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) self.is_shortened = self._label.is_shortened 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]) '''The color of the text when the widget is disabled, in the (r, g, b, a) format. .. versionadded:: 1.8.0 :attr:`disabled_color` is a :class:`~kivy.properties.ListProperty` and defaults to [1, 1, 1, .3]. ''' 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 constraints. 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. ''' base_direction = OptionProperty(None, options=['ltr', 'rtl', 'weak_rtl', 'weak_ltr', None], allownone=True) '''Base direction of text, this impacts horizontal alignment when :attr:`halign` is `auto` (the default). Available options are: None, "ltr" (left to right), "rtl" (right to left) plus "weak_ltr" and "weak_rtl". .. note:: This feature requires the Pango text provider. .. note:: Weak modes are currently not implemented in Kivy text layout, and have the same effect as setting strong mode. .. versionadded:: 1.11.0 :attr:`base_direction` is an :class:`~kivy.properties.OptionProperty` and defaults to None (autodetect RTL if possible, otherwise LTR). ''' text_language = StringProperty(None, allownone=True) '''Language of the text, if None Pango will determine it from locale. This is an RFC-3066 format language tag (as a string), for example "en_US", "zh_CN", "fr" or "ja". This can impact font selection, metrics and rendering. For example, the same bytes of text can look different for `ur` and `ar` languages, though both use Arabic script. .. note:: This feature requires the Pango text provider. .. versionadded:: 1.11.0 :attr:`text_language` is a :class:`~kivy.properties.StringProperty` and defaults to None. ''' font_context = StringProperty(None, allownone=True) '''Font context. `None` means the font is used in isolation, so you are guaranteed to be drawing with the TTF file resolved by :attr:`font_name`. Specifying a value here will load the font file into a named context, enabling fallback between all fonts in the same context. If a font context is set, you are not guaranteed that rendering will actually use the specified TTF file for all glyphs (Pango will pick the one it thinks is best). If Kivy is linked against a system-wide installation of FontConfig, you can load the system fonts by specifying a font context starting with the special string `system://`. This will load the system fontconfig configuration, and add your application-specific fonts on top of it (this imposes a signifficant risk of family name collision, Pango may not use your custom font file, but pick one from the system) .. note:: This feature requires the Pango text provider. .. versionadded:: 1.11.0 :attr:`font_context` is a :class:`~kivy.properties.StringProperty` and defaults to None. ''' font_family = StringProperty(None, allownone=True) '''Font family, this is only applicable when using :attr:`font_context` option. The specified font family will be requested, but note that it may not be available, or there could be multiple fonts registered with the same family. The value can be a family name (string) available in the font context (for example a system font in a `system://` context, or a custom font file added using :class:`kivy.core.text.FontContextManager`). If set to `None`, font selection is controlled by the :attr:`font_name` setting. .. note:: If using :attr:`font_name` to reference a custom font file, you should leave this as `None`. The family name is managed automatically in this case. .. note:: This feature requires the Pango text provider. .. versionadded:: 1.11.0 :attr:`font_family` is a :class:`~kivy.properties.StringProperty` and defaults to None. ''' font_name = StringProperty(DEFAULT_FONT) '''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'. This value is taken from :class:`~kivy.config.Config`. ''' font_size = NumericProperty('15sp') '''Font size of the text, in pixels. :attr:`font_size` is a :class:`~kivy.properties.NumericProperty` and defaults to 15sp. ''' font_features = StringProperty() '''OpenType font features, in CSS format, this is passed straight through to Pango. The effects of requesting a feature depends on loaded fonts, library versions, etc. For a complete list of features, see: https://en.wikipedia.org/wiki/List_of_typographic_features .. note:: This feature requires the Pango text provider, and Pango library v1.38 or later. .. versionadded:: 1.11.0 :attr:`font_features` is a :class:`~kivy.properties.StringProperty` and defaults to an empty string. ''' 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.10.0 :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.10.0 :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('auto', options=['left', 'center', 'right', 'justify', 'auto']) '''Horizontal alignment of the text. :attr:`halign` is an :class:`~kivy.properties.OptionProperty` and defaults to 'auto'. Available options are : auto, left, center, right and justify. Auto will attempt to autodetect horizontal alignment for RTL text (Pango only), otherwise it behaves like `left`. .. 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.10.1 Added `auto` option .. 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.10.0 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]. ''' outline_width = NumericProperty(None, allownone=True) '''Width in pixels for the outline around the text. No outline will be rendered if the value is None. .. note:: This feature requires the SDL2 text provider. .. versionadded:: 1.10.0 :attr:`outline_width` is a :class:`~kivy.properties.NumericProperty` and defaults to None. ''' outline_color = ListProperty([0, 0, 0]) '''The color of the text outline, in the (r, g, b) format. .. note:: This feature requires the SDL2 text provider. .. versionadded:: 1.10.0 :attr:`outline_color` is a :class:`~kivy.properties.ListProperty` and defaults to [0, 0, 0]. ''' disabled_outline_color = ListProperty([0, 0, 0]) '''The color of the text outline when the widget is disabled, in the (r, g, b) format. .. note:: This feature requires the SDL2 text provider. .. versionadded:: 1.10.0 :attr:`disabled_outline_color` is a :class:`~kivy.properties.ListProperty` and defaults to [0, 0, 0]. ''' 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`. ''' is_shortened = BooleanProperty(False) '''This property indicates if :attr:`text` was rendered with or without shortening when :attr:`shorten` is True. .. versionadded:: 1.10.0 :attr:`is_shortened` is a :class:`~kivy.properties.BooleanProperty` and defaults to False. ''' 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:`split_str` 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). ''' ellipsis_options = DictProperty({}) '''Font options for the ellipsis string('...') used to split the text. Accepts a dict as option name with the value. Only applied when :attr:`markup` is true and text is shortened. All font options which work for :class:`Label` will work for :attr:`ellipsis_options`. Defaults for the options not specified are taken from the surronding text. .. code-block:: kv Label: text: 'Some very long line which will be cut' markup: True shorten: True ellipsis_options: {'color':(1,0.5,0.5,1),'underline':True} .. versionadded:: 2.0.0 :attr:`ellipsis_options` is a :class:`~kivy.properties.DictProperty` and defaults to `{}` (the empty dict). ''' 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 occurrence 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 occurrence 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 SDL2 or Pango text provider. .. versionadded:: 1.10.0 :attr:`font_hinting` is an :class:`~kivy.properties.OptionProperty` and defaults to `'normal'`. ''' font_kerning = BooleanProperty(True) '''Whether kerning is enabled for font rendering. You should normally only disable this if rendering is broken with a particular font file. .. note:: This feature requires the SDL2 text provider. .. versionadded:: 1.10.0 :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.
def _draw_current_map(self): def _calc_heat_pct(heat_value, heat_min, heat_range): if heat_value is not None and heat_range > 0: return int(((heat_value - heat_min) / heat_range) * 100.0) else: return 0 left = self.pos[0] bottom = self.pos[1] self.canvas.clear() heat_width_step = self.HEAT_MAP_WIDTH_STEP path_count = len(self._scaled_paths.keys()) heat_width = (self.heat_width_scale * self.height) + ((path_count - 1) * heat_width_step) with self.canvas: Color(*self.track_color) Line(points=self._scaled_map_points, width=self.track_width_scale * self.height, closed=True, cap='round', joint='round') color_gradient = HeatColorGradient() # draw all of the traces for key, path_points in self._scaled_paths.iteritems(): heat_path = self._heat_map_values.get(key) if heat_path: # draw heat map point_count = len(path_points) heat_min = self.heat_min heat_range = self.heat_max - heat_min value_index = 0 current_heat_pct = 0 i = 0 line_points = [] try: line_points.extend([path_points[i], path_points[i + 1]]) current_heat_pct = _calc_heat_pct(heat_path[value_index], heat_min, heat_range) while i < point_count - 2: heat_pct = _calc_heat_pct(heat_path[value_index], heat_min, heat_range) if heat_pct != current_heat_pct: heat_color = color_gradient.get_color_value(heat_pct / 100.0) Color(*heat_color) Line(points=line_points, width=heat_width, closed=False, joint='miter', cap='round') line_points = [path_points[i - 2], path_points[i - 1]] current_heat_pct = heat_pct line_points.extend([path_points[i], path_points[i + 1]]) value_index += 1 i += 2 heat_width -= heat_width_step except IndexError: # if the number of heat values mismatch the heat map points, terminate early pass else: # draw regular map trace Color(*self._paths[key].color) Line(points=path_points, width=self.path_width_scale * self.height, closed=True, cap='square', joint='miter') target_size = (self.target_width_scale * self.height) * self.target_scale # draw start point if GeoPoint.is_valid(self.start_point): Color(*self.start_point_color) scaled_point = self._scale_geopoint(self.start_point) Rectangle(texture=TrackMapView.start_image.texture, pos=self._center_point(scaled_point, (target_size, target_size)), size=[target_size, target_size]) # draw finish point if GeoPoint.is_valid(self.finish_point): Color(*self.finish_point_color) scaled_point = self._scale_geopoint(self.finish_point) Rectangle(texture=TrackMapView.finish_image.texture, pos=self._center_point(scaled_point, (target_size, target_size)), size=[target_size, target_size]) # draw the sector points sector_count = 0 for sector_point in self.sector_points: sector_count += 1 scaled_point = self._scale_geopoint(sector_point) label = CoreLabel(text='{:>2}'.format(sector_count), font_size=target_size * 0.8, font_name='resource/fonts/ASL_regular.ttf') label.refresh() texture = label.texture centered_point = self._center_point(scaled_point, texture.size) Color(*self.sector_point_color) Rectangle(source='resource/trackmap/sector_64px.png', pos=self._center_point(scaled_point, texture.size), size=[target_size, target_size]) Color(0.0, 0.0, 0.0, 1.0) # Tweak font position to improve centering. SHould be a better way to do this trim_x = texture.size[0] * 0.1 trim_y = -texture.size[1] * 0.05 Rectangle(size=texture.size, pos=(centered_point[0] + trim_x, centered_point[1] + trim_y), texture=texture) # draw the dynamic markers marker_size = (self.marker_width_scale * self.height) * self.marker_scale for key, marker_point in self._marker_points.iteritems(): scaled_point = self._scale_point(marker_point, self.height, left, bottom) Color(*marker_point.color) self._marker_locations[key] = Line(circle=(scaled_point.x, scaled_point.y, marker_size), width=marker_size, closed=True) Color(1.0, 1.0, 1.0, 1.0)
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) '''
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): '''Render text that is displayed in the canvas. The position x, y is given in matplotlib coordinates. A `GraphicsContextKivy` is given to render according to the text properties such as color, size, etc. An angle is given to change the orientation of the text when needed. If the text is a math expression it will be rendered using a MathText parser. ''' if mtext: transform = mtext.get_transform() ax, ay = transform.transform_point(mtext.get_position()) angle_rad = mtext.get_rotation() * np.pi / 180. dir_vert = np.array([np.sin(angle_rad), np.cos(angle_rad)]) if mtext.get_rotation_mode() == "anchor": # if anchor mode, rotation is undone first v_offset = np.dot(dir_vert, [(x - ax), (y - ay)]) ax = ax + v_offset * dir_vert[0] ay = ay + v_offset * dir_vert[1] w, h, d = self.get_text_width_height_descent(s, prop, ismath) ha, va = mtext.get_ha(), mtext.get_va() if ha == "center": ax -= w / 2 elif ha == "right": ax -= w if va == "top": ay -= h elif va == "center": ay -= h / 2 if mtext.get_rotation_mode() != "anchor": # if not anchor mode, rotation is undone last v_offset = np.dot(dir_vert, [(x - ax), (y - ay)]) ax = ax + v_offset * dir_vert[0] ay = ay + v_offset * dir_vert[1] x, y = ax, ay x += self.widget.x y += self.widget.y if ismath: self.draw_mathtext(gc, x, y, s, prop, angle) else: 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)) if prop.get_style() == 'italic': plot_text.italic = True if weight_as_number(prop.get_weight()) > 500: plot_text.bold = True plot_text.refresh() with self.widget.canvas: if isinstance(angle, float): PushMatrix() Rotate(angle=angle, origin=(int(x), int(y))) Rectangle(pos=(int(x), int(y)), texture=plot_text.texture, size=plot_text.texture.size) PopMatrix() else: Rectangle(pos=(int(x), int(y)), texture=plot_text.texture, size=plot_text.texture.size)
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.
def get_label_texture(self, index, **kw): label = CoreLabel(text=self.value_str(self.slot_value(index)), font_size=self.font_size, **kw) label.refresh() return label.texture
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.
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", ) 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(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 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() if self._label.__class__ is CoreMarkupLabel: self.refs = self._label.refs self.anchors = self._label.anchors 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.iteritems(): 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 # 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. (It is 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("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 trouble. 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`, default to 'DroidSans'. """ 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) """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`, default 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`, 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. .. 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 texture_size or set a text_size. """ 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. .. 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 texture_size or set a text_size. """ 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. 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 :func:`texture_update` function before accessing :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) """Indicates 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) """ 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`, default to False. """ markup = BooleanProperty(False) """ .. versionadded:: 1.1.0 If true, the text will be rendered with :class:`~kivy.core.text.markup.MarkupLabel`: you can change the style of the text using tags. Check :doc:`api-kivy.core.text.markup` documentation for more information. :data:`markup` is a :class:`~kivy.properties.BooleanProperty`, default to False. """ refs = DictProperty({}) """ .. versionadded:: 1.1.0 List of ``[ref=xxx]`` markup put into the text, with the bounding box of all the words contained in a ref, 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" have a bounding box set 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 is working only with markup text. You need :data:`markup` set to True. """ anchors = DictProperty({}) '''