def renderText(self, text, rect, fontSize, surf, colour): b = False while not b: lines = [] line = '' words = text.split(' ') font = pygame.font.Font(None, fontSize) for word in words: test_line = line + word + ' ' # Build the line while the words fit. if font.size(test_line)[0] < rect.width: line = test_line else: lines.append(line) line = word + ' ' lines.append(line) '''Mira si cap el text, sino fa la font mes petita i intenta de nou''' total_height = font.size(lines[0])[1] * len(lines) if total_height > rect.height: fontSize -= 2 else: b = True acum_heigth = 0 yCord = rect.y + 5 for line in lines: if line != "": textline = font.render(line, 1, colour) surf.blit(textline, (rect.x, yCord)) yCord = yCord + font.size(line)[1] + 3 acum_heigth += font.size(line)[1]
def prepare_paragraph(text, width, size="normal", colour=(0,0,0)): font = FONTS[size] lines = [] words = text.split() if words: lastline = None line = words[0] for i in range(1,len(words)): lastline = line line = line+" "+words[i] w,h = font.size(line) if w > width: lines.append(lastline) line = words[i] else: line = "" lines.append(line) parawidth = max(font.size(each)[0] for each in lines) lineheight = font.get_height() paraheight = lineheight*len(lines) paragraph = Surface((parawidth,paraheight),pygame.SRCALPHA) paragraph.fill((255,255,255,0)) for y,line in enumerate(lines): text = prepare(line,size,colour) paragraph.blit(text,(0,y*lineheight)) return paragraph
def drawText(surface, text, color, rect, font, aa=False, bkg=None): # This function is used to create wrapped text rect = pygame.Rect(rect) y = rect.top lineSpacing = -2 fontHeight = font.size("Tg")[1] while text: i = 1 if y + fontHeight > rect.bottom: break while font.size(text[:i])[0] < rect.width and i < len(text): i += 1 if i < len(text): i = text.rfind(" ", 0, i) + 1 if bkg: image = font.render(text[:i], 1, color, bkg) image.set_colorkey(bkg) else: image = font.render(text[:i], aa, color) surface.blit(image, (rect.left, y)) y += fontHeight + lineSpacing text = text[i:] return text
def wrapText(text, font, width): lineWidth = font.size(text)[0] if lineWidth > width: words = text.split(' ') i = 1 while i < len(words): currLine = ' '.join(words[:-i]) if font.size(currLine)[0] <= width: return currLine + "\n" + wrapText(' '.join(words[len(words)-i:]),font,width) i += 1 else: return text
def wrapText(text, font, width): lineWidth = font.size(text)[0] if lineWidth > width: words = text.split(' ') i = 1 while i < len(words): currLine = ' '.join(words[:-i]) if font.size(currLine)[0] <= width: return currLine + "\n" + wrapText( ' '.join(words[len(words) - i:]), font, width) i += 1 else: #print text return text
def screen(self,surface,pos,fgcolor=(128,128,125),font=None,interline=0): fgcolor = [fgcolor] px,y = pos mono = True if not font: font = Text.defaultfont if font.size('i')!=font.size('x'): mono = False char_w,char_h = font.size(' ') char_h += interline style_cmd = {'+':True,'-':False,'b':font.set_bold,'i':font.set_italic,'u':font.set_underline} bz = self.baliz def set_style(pos): while True: if bz and pos == bz[0][0]: _,mode,style,color,value = bz.pop(0) if mode: style_cmd[style](style_cmd[mode]) elif color: if value: fgcolor.append(Color(int(value,16)<<8)) else: fgcolor.pop() else: break rec = Rect(pos,(0,0)) pos = 0 set_style(pos) if mono: for lines in self: for line in lines: x = px for char in line: rec = rec.unionall([(surface.blit(font.render(char,1,fgcolor[-1]),(x,y))),rec]) x += char_w pos += 1 set_style(pos) y += char_h pos += 1 set_style(pos) return rec for lines in self: for line in lines: x = px for char in line: x = surface.blit(font.render(char,1,fgcolor[-1]),(x,y)) rec = rec.unionall([x,rec]) x = x.right pos += 1 set_style(pos) y += char_h pos += 1 set_style(pos) return rec
def scores(self, score_button, screen): score_button.draw_button() fonta = pygame.font.Font(None, 72) texta = fonta.render("ALL-TIME", 1, (255, 255, 255)) widtha, heighta = fonta.size("ALL-TIME") recta = pygame.Rect(screen.get_width() / 2 - widtha / 2, screen.get_height() / 20, widtha, heighta) screen.blit(texta, recta) self.fontb = pygame.font.Font(None, 72) textb = self.fontb.render("HIGH SCORES:", 1, (255, 255, 255)) widthb, heightb = self.fontb.size("HIGH SCORES:") rectb = pygame.Rect(screen.get_width() / 2 - widthb / 2, screen.get_height() / 20 + heighta, widthb, heightb) screen.blit(textb, rectb) with open('hs.txt'): hscores = [line.rstrip('\n') for line in open('hs.txt')] top_scores = [] for i in range(0, 9): max1 = 0 for j in range(len(hscores)): if int(hscores[j]) > max1: max1 = int(hscores[j]) hscores.remove(str(max1)) top_scores.append(max1) for i in range(0, 9): current_score = top_scores[i] font = pygame.font.Font(None, 46) text = font.render(str(i+1) + ". " + str(current_score), 1, (255, 255, 255)) width, height = font.size(str(i+1) + ". " + str(current_score)) rect = pygame.Rect(0, rectb.bottom + 75 * (i + 1), width, height) rect.left = rectb.left screen.blit(text, rect)
def create_window(): """Return draw function, which takes a text parameter.""" pygame.init() pygame.display.set_caption('stopwatch') resolution = [size // 2 for size in pygame.display.list_modes()[0]] surface = pygame.display.set_mode(resolution) # Get highest font size that fits resolution width. font_size = int(resolution[1] / 1.2) font_size_fits = False max_string_length = resolution[0] // 8 * 7 while not font_size_fits: font = pygame.font.SysFont('courier new', font_size) font_rect = font.size('00:00:00,00') if font_rect[0] > max_string_length: font_size = font_size - 10 else: font_size_fits = True # Get the point to draw the font in the midle of the screen. font_blit_point = (resolution[0] // 16, resolution[1] // 2 - font_rect[1] // 2) def draw(text): """Draw text.""" # Fill the screen with white, to erase the previous time. surface.fill(THECOLORS['white']) surface.blit(font.render(text, 1, THECOLORS['black']), font_blit_point) pygame.display.flip() return draw
def drawTextCentered(self, text, size, x, y): font = pygame.font.Font("arcticOS/font.ttf", size) bounds = font.size(text) x = x - (bounds[0] / 2) y = y - (bounds[1] / 2) rendered_text = font.render(text, True, self.color_black) self.display.blit(rendered_text, (x, y))
def index_fx(screen, it, font, msg): gl.NOT_HOVERED = 0 fxpos = (it[0][0] - 10, it[0][1] + (font.size(it[1])[1] / 2) - 13, it[0][2], it[0][3]) show_message(".", fxpos, 16, ("bold")) show_message("%s%s%s" % (" " * 20, msg, " " * 20), "bottom", 12) return fxpos
def __init__(self, text, bgcolor, max_size, style): font = pygame.font.SysFont(style["font"]["family"], style["font"]["size"]) font_height = font.size("Tg")[1] line_spacing = style["paragraph"]["spacing"] color = style["font"]["color"] margin = style["text"]["margin"] width, max_height = max_size paragraphs = text.split('\n') lines = [] for p in paragraphs: p_lines, _ = self._split_text(p, font, width, font_height, line_spacing, max_height) lines.extend(p_lines) lines.append('') lines.pop() # remove last extra line. height = len(lines) * (font_height + line_spacing) - line_spacing size = Vector(width, height) self.image = Surface(size + 2 * margin) self.image.fill(bgcolor) offset = Vector(*margin) for line in lines: text_image = font.render(line, True, color, bgcolor) text_image.set_colorkey(bgcolor) self.image.blit(text_image, offset) offset += Vector(0, font_height + line_spacing) self.rect = self.image.get_rect()
def render_text(self, con, text: str, position: Tuple[int, int], fg_col, break_on_comma=False): font = self.fonts.get("mini") if break_on_comma and "," in text: text_lines = text.split(",") _longest = max(text_lines, key=len) _width = font.size(_longest)[0] text_surface = pygame.Surface( (_width, (font.get_linesize() * len(text_lines)))).convert_alpha() text_surface.fill(CONFIG.get_colour("empty")) y_offset = 0 for line in text_lines: print_pos = (0, y_offset) self.render_text(text_surface, line.strip(), (0, y_offset), fg_col, font) y_offset += font.get_linesize() else: text_surface = font.render(text, False, CONFIG.get_colour(fg_col)) con.blit(text_surface, position)
def get_cursor(self): """ get a rect representing the position of the cursor on the editor image """ k, font, txt = self._cursor, self.font, self.txt index2pixel = self._index2pixel return Rect(index2pixel(k), font.size(txt[k]))
def wrap_text(text, width): lines = [[]] for word in text.split(): if font.size(' '.join(lines[-1] + [word]))[0] < width - PADDING_X * 2: lines[-1].append(word) else: lines.append([' ', word]) return [' '.join(line) for line in lines]
def fontSize(): pygame.font.init() size = None for i in range(30): font = pygame.font.SysFont("norasi", i, True) text_width, text_height = font.size("0") print(text_width, text_height) if
def verbose_info(screen, new_img, file, num_imgs): # main engine wait_cursor() paint_screen(screen, gl.BLACK) try: (uniquecolors_rect, total_colors, row, font, im, verb) = print_verbose_info(screen, new_img, file, num_imgs) except: print 'print verbose' #(uniquecolors_rect, total_colors, row, font, im, verb) = junk_rect()# # uniquecolors_rect = junk_rect()# # total_colors = ""# verb = verbose(screen, file)# (uniquecolors_rect, total_colors, row, font, im) = verb.colors() #return if gl.SHOW_EXIFBUTTON: exif_rect = imgv_button(screen, " Exif Data ", 5, gl.ROW_SEP + 435, None) (esc_rect, close_font) = close_button(screen) normal_cursor() transparency = 0 while 1: event = pygame.event.poll() pygame.time.wait(1) check_quit(event) cursor = pygame.mouse.get_pos() hover_cursor(cursor, (esc_rect, exif_rect, uniquecolors_rect)) if gl.SHOW_EXIFBUTTON: hover_button(exif_rect, cursor, screen, " Exif Data ", 5, gl.ROW_SEP + 435, None) if gl.UNIQUE_COLORS == None and gl.SHOW_EXIFBUTTON and total_colors != "": hover_button(uniquecolors_rect, cursor, screen, " Unique colors ", (font.size(total_colors)[0] + 230), row, None) show_message(screen, convert_times(ctime(), 0), "bottom", 15, ("transparent")) if event.type == MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0]: if uniquecolors_rect != junk_rect(): if uniquecolors_rect.collidepoint(cursor): wait_cursor() gl.UNIQUE_COLORS = comma_it(len(dict.fromkeys(im.getdata()))) # determine unique colors before_color = gl.MSG_COLOR if gl.MSG_COLOR == gl.SILVER: gl.MSG_COLOR = (142, 142, 142) else: gl.MSG_COLOR = gl.SILVER show_message(screen, "Unique colors: %s%s" % (gl.UNIQUE_COLORS, ' ' * 12), ((font.size(total_colors)[0] + 235), row), 12, (""), (14, before_color)) gl.MSG_COLOR = before_color normal_cursor() if exif_rect.collidepoint(cursor): wait_cursor() try: verb.exif_data(file) except: break normal_cursor() if esc_rect.collidepoint(cursor): before_exit() break if event.type == KEYDOWN and event.key not in (K_LALT, K_RALT, K_LCTRL, K_RCTRL, K_TAB): before_exit() break
def block_size(text, font): brokenText = text.replace("\r\n", "\n").replace("\r", "\n").split("\n") height = len(brokenText) * font.get_linesize() width = 0 for line in brokenText: line_width, line_height = font.size(line) width = max(width, line_width) return width, height
def __init__(self, filename, size, charset='abcdefghijklmnopqrstuvwxyz' +\ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +\ '1234567890;:,.!?%&"\' '): #filename = os.path.join('fonts', filename) self.filename = filename self.charset = charset self.charmap = {} font = pygame.font.Font(filename, size) self.descent = font.get_descent() self.w, self.h = font.size(self.charset) self.w += len(self.charset) * self.characterSpacing self.lineSize = self.h if self.w > self.maxTextureWidth: self.h = (self.w / self.maxTextureWidth + 1) * self.h self.w = self.maxTextureWidth self.tw, self.th = resource.pow2(self.w), resource.pow2(self.h) data = chr(0) * self.tw * self.th * 4 surface = pygame.image.fromstring(data, (self.tw, self.th), 'RGBA') x, y = 0.0, 0.0 for c in charset: render = font.render(c, True, (255, 255, 255)) render = pygame.transform.flip(render,False,True) # hack somehow my shit was upside down cw, ch = font.size(c) if x + cw >= self.tw: x = 0.0 y += self.lineSize surface.blit(render, (x, y)) self.charmap[c] = (x/self.tw, (self.th-y-self.lineSize)/self.th, (x+cw)/self.tw, (self.th-y)/self.th), cw x += cw + self.characterSpacing self.tex = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, self.tex) glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexImage2D(GL_TEXTURE_2D, 0, 4, self.tw, self.th, 0, GL_RGBA, GL_UNSIGNED_BYTE, pygame.image.tostring(surface, 'RGBA', True))
def wrap_text(self, text, width): """Returns list of strings that all fit within pixel width using given font""" results = [] seperator = " " _split_words = text.split() font = self.fonts.get("mini") # Quick check if the whole string fits # (also removes extra whitespace) _check = seperator.join(_split_words) if font.size(_check)[0] <= width: return [ text, ] # do this until we're out of words while len(_split_words) > 0: # temporary variable with the last result that fit _last_fit = "" for i in range(1, len(_split_words) + 1): # make line with one more word than last time _check = seperator.join(_split_words[:i]) # check if it's too long, in which case we store the last one that fit if (font.size(_check)[0] > width): # add last fit results.append(_last_fit) # remove those from the list _split_words = _split_words[i - 1:] # kill the loop so we can start over break elif i == len(_split_words): # this was the last iteration # if it reaches here, we know the remaining part is short enough results.append(_check) # still remove the part we stored _split_words = _split_words[i:] else: # it fits, so prep to try one longer _last_fit = _check # done while, return results return results
def wrapText(text, font, width): """ Wraps a line of text depending on font size @param text text to wrapped @param font font used @param width width in pixels """ lineWidth = font.size(text)[0] if lineWidth > width: words = text.split(' ') i = 1 while i < len(words): currLine = ' '.join(words[:-i]) if font.size(currLine)[0] <= width: return currLine + "\n" + wrapText(' '. join(words[len(words)-i:]),font,width) i += 1 else: return text
def wrap(text, width, font): """Wrap a line of text, returning a list of lines.""" lines = [] while text: if font.size(text)[0] <= width: return lines + [text] try: i = string.rindex(text, ' ') while font.size(text[:i])[0] > width: i = string.rindex(text, ' ', 0, i) except ValueError: i = len(text)-1 while font.size(text[:i])[0] > width and i: i = i - 1 if not i: raise ValueError, 'width %d too narrow' % width lines.append(text[:i]) text = string.lstrip(text[i:]) return lines
def createText(text, color = grey, background_color = black, font = largeFont): """ Create a bitmap with the specified text, and return it along with its width and height """ # Draw the text to a new image textPic = font.render(text, True, color, background_color) # Get the size of the text textW, textH = font.size(text) return textPic, textW, textH
def draw_text_centered(surface, font, text, color, rect): text_w, text_h = font.size(text) surface.blit( font.render( text, True, color, ), (rect[0] + rect[2] // 2 - text_w // 2, rect[1] + rect[3] // 2 - text_h // 2, text_w, text_h), )
def file_master(screen, file_names, place, marker, menu_items, msg, down, button_op): paint_screen(gl.BLACK) show_message(msg, down, 10, ("bold", "transparent")) font = pygame.font.Font(gl.FONT_NAME, 9) font.set_bold(1) (esc_rect, esc_font) = close_button(screen) font_height = font.size(file_names[0])[1] screen_height = screen.get_height() name_max = 16 max_file_width = 116 line = 65 # leave room at top of screen for other stuff col = 5 count = 0 back_rect = forward_rect = sort_rect = junk_rect() for name in file_names[place:]: count = count + 1 place = place + 1 marker = marker + 1 if count >= gl.MAX_SCREEN_FILES or place >= len(file_names): ren_name = os.path.basename(name) if len(ren_name) > name_max: ren_name = ren_name[:name_max] + '...' # truncate if ren_name[-4:] == '....': ren_name = ren_name[:-1] # 3 .'s are enough ren = font.render(ren_name, 1, gl.MSG_COLOR, gl.BLACK) if (place + 1) < len(file_names): forward_rect = imgv_button(screen, " Next ", 10, 18, "topright") if (((place + 1) - gl.MAX_SCREEN_FILES) > 1): back_rect = imgv_button(screen, " Previous ", 10, 18, "topleft") if not gl.SORT_HIT: sort_rect = imgv_button(screen, " Sort ", 13, 42, "midtop") ren_rect = ren.get_rect() ren_rect[0] = col ren_rect[1] = line menu_items.append((ren_rect, name)) screen.blit(ren, ren_rect) update(ren_rect) return (file_names, menu_items, 1, place, marker, forward_rect, back_rect, sort_rect) ren_name = os.path.basename(name) if len(ren_name) > name_max: ren_name = ren_name[:name_max] + '...' if ren_name[-4:] == '....': ren_name = ren_name[:-1] ren = font.render(ren_name, 1, gl.MSG_COLOR, gl.BLACK) ren_rect = ren.get_rect() ren_rect[0] = col ren_rect[1] = line menu_items.append((ren_rect, name)) screen.blit(ren, ren_rect) line = line + 12 if (line + font_height) >= (screen_height - 15): line = 65 col = col + max_file_width update(ren_rect) return (file_names, menu_items, 0, place, marker, forward_rect, back_rect, sort_rect)
def _index2pixel(self, i): font, lines, txt = self.font, self._lines, self.txt wraps = self._wraps + [len(txt)] index2line = self._index2line l = index2line(i) x = font.size(''.join(txt[wraps[l]:i]))[0] y = lines[l].rect.y return x, y
def _update(self, l): bkg, color, font = self.bkg, self.color, self.font spacing, dest, rect_w = self.spacing, self._dest, self.rect.w bkg_img, image = self._image, self.image lines, txt, wraps = self._lines, self.txt, self._wraps tokenize = self._tokenize Line = _Line tokens = tokenize(txt[wraps[l]:]) dest.y = sum(line.image.get_height() + spacing for line in lines[:l]) wraps = wraps[:l + 1] k = wraps[-1] linebuff = [] L = [l] # a list of updated lines for token in tokens: if token == '\n': k += 1 # increment k (so the \n will be on this line) wraps.append(k) # a space is the visual representation of the \n character linebuff.append(' ') _linebuff = [] elif font.size(''.join(linebuff + [token]))[0] < rect_w: k += len(token) linebuff.append(token) continue else: wraps.append( k) # k is the position of the previous space token k += len(token) _linebuff = [token] lines.insert(l + 1, Line(Surface((0, 0)), Rect(0, 0, 0, 0))) line = font.render(''.join(linebuff), 0, color, bkg) line = Line(line, Rect(dest.topleft, line.get_size())) lines[l].clear(image, bkg_img) lines[l] = line dest.y += line.image.get_height() + spacing linebuff = _linebuff l += 1 L.append(l) line = font.render(''.join(linebuff), 0, color, bkg) line = Line(line, Rect(dest.topleft, line.get_size())) lines[l].clear(image, bkg_img) lines[l] = line for line in [lines[l] for l in L]: image.blit(line.image, line.rect) self._wraps = wraps
def exif_data(self, filen): paint_screen(gl.BLACK) close_button(self.screen) if not self.show_exif: gl.SHOW_EXIFBUTTON = 0 return exif_info = [] filename = gl.files[filen] try: file = open(filename, "rb") except: exif_info.append("%s unreadable" % filename) gl.SHOW_EXIFBUTTON = 0 return data = exif.process_file(file) if not data: font_size = 13 font = pygame.font.Font(gl.FONT_NAME, font_size) no_exif_msg = "No Exif information found" show_message( no_exif_msg, ((self.screen.get_width() / 2) - (font.size(no_exif_msg)[0] / 2), self.screen.get_height() / 2), font_size, ("bold", "transparent"), ) gl.SHOW_EXIFBUTTON = 0 return x = data.keys() x.sort() for i in x: if i in ("JPEGThumbnail", "TIFFThumbnail"): continue try: exif_info.append("%s: %s" % (i, data[i].printable)) except: exif_info.append("error", i, '"', data[i], '"') gl.SHOW_EXIFBUTTON = 0 pos = 25 show_message("Exif Information", "top", 13, ("underline", "bold", "transparent")) try: for line in exif_info: if type(line) is StringType and len(line) <= 250: # parachutes on long lines without this exif_font = pygame.font.Font(gl.FONT_NAME, 9) ren = exif_font.render(line, 1, gl.MENU_COLOR) ren_rect = ren.get_rect() ren_rect[0] = 14 ren_rect[1] = pos self.screen.blit(ren, ren_rect) pos = pos + 9 except: print "Couldn't exif" # pass flip()
def __init__(self, filename, size, charset='abcdefghijklmnopqrstuvwxyz' +\ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +\ '1234567890;:,.!?%&"\' '): filename = os.path.join('fonts', filename) self.filename = filename self.charset = charset self.charmap = {} font = pygame.font.Font(filename, size) self.descent = font.get_descent() self.w, self.h = font.size(self.charset) self.w += len(self.charset) * self.characterSpacing self.lineSize = self.h if self.w > self.maxTextureWidth: self.h = (self.w / self.maxTextureWidth + 1) * self.h self.w = self.maxTextureWidth self.tw, self.th = res.pow2(self.w), res.pow2(self.h) data = chr(0) * self.tw * self.th * 4 surface = pygame.image.fromstring(data, (self.tw, self.th), 'RGBA') x, y = 0.0, 0.0 for c in charset: render = font.render(c, True, (255, 255, 255)) cw, ch = font.size(c) if x + cw >= self.tw: x = 0.0 y += self.lineSize surface.blit(render, (x, y)) self.charmap[c] = (x/self.tw, (self.th-y-self.lineSize)/self.th, (x+cw)/self.tw, (self.th-y)/self.th), cw x += cw + self.characterSpacing self.tex = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, self.tex) glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexImage2D(GL_TEXTURE_2D, 0, 4, self.tw, self.th, 0, GL_RGBA, GL_UNSIGNED_BYTE, pygame.image.tostring(surface, 'RGBA', True))
def length_splitter(font, text, maxlength): ret_list = [] explode = text.split() t_str = "" while len(explode) > 0: if font.size(t_str + explode[0])[0] > maxlength: ret_list.append(t_str) t_str = "" else: t_str += explode.pop(0) + " " if len(explode) == 0: ret_list.append(t_str) return ret_list
def _update(self, l): bkg, color, font = self.bkg, self.color, self.font spacing, dest, rect_w = self.spacing, self._dest, self.rect.w bkg_img, image = self._image, self.image lines, txt, wraps = self._lines, self.txt, self._wraps tokenize = self._tokenize Line = _Line tokens = tokenize(txt[wraps[l]:]) dest.y = sum(line.image.get_height() + spacing for line in lines[:l]) wraps = wraps[:l + 1] k = wraps[-1] linebuff = [] L = [l] # a list of updated lines for token in tokens: if token == '\n': k += 1 # increment k (so the \n will be on this line) wraps.append(k) # a space is the visual representation of the \n character linebuff.append(' ') _linebuff = [] elif font.size(''.join(linebuff + [token]))[0] < rect_w: k += len(token) linebuff.append(token) continue else: wraps.append(k) # k is the position of the previous space token k += len(token) _linebuff = [token] lines.insert(l + 1, Line(Surface((0, 0)), Rect(0, 0, 0, 0))) line = font.render(''.join(linebuff), 0, color, bkg) line = Line(line, Rect(dest.topleft, line.get_size())) lines[l].clear(image, bkg_img) lines[l] = line dest.y += line.image.get_height() + spacing linebuff = _linebuff l += 1 L.append(l) line = font.render(''.join(linebuff), 0, color, bkg) line = Line(line, Rect(dest.topleft, line.get_size())) lines[l].clear(image, bkg_img) lines[l] = line for line in [lines[l] for l in L]: image.blit(line.image, line.rect) self._wraps = wraps
def drawTextCentered(surface, text, color = grey, backgroundColor = black, font = mediumFont): # Draw the text to a new image textPic = font.render(text, True, color, backgroundColor) # Get the size of the text and the surface textW, textH = font.size(text) surfaceRect = surface.get_rect() # Calculate position for the text on the center of the surface x = surfaceRect.centerx - textW / 2 y = surfaceRect.centery - textH / 2 # Draw the text picture to the middle of the surface surface.blit(textPic, (x,y))
def make_clock(self): w, h = self.surface.get_width(), _CLOCK_HEIGHT font = pygame.font.SysFont('arialblack', 16) fh = font.size('0123456789')[1] surface = pygame.Surface((w, h)) surface.fill((0, 128, 255)) for hour in range(24): x = int(round(hour * w / 24.0)) x1 = int(round((hour + 0.5) * w / 24.0)) pygame.draw.line(surface, (255, 255, 255), (x, 0), (x, h)) pygame.draw.line(surface, (255, 255, 255), (x1, 0), (x1, h - fh)) text = font.render(str(hour), True, (255, 255, 255)) surface.blit(text, (x1 - int(round(text.get_width() / 2.0)), h - fh)) self.clock = surface
def __init__(self, position, text, font, background_colour, text_colour, onclick_callback, hover_colour=None, click_colour=None, size=None): self.x, self.y = position self.text = text self.background_colour = background_colour self.onclick_callback = onclick_callback self.hover_colour = hover_colour if hover_colour is not None else background_colour self.click_colour = click_colour if click_colour is not None else background_colour label_size = font.size(self.text) self.label = Text(text, font, text_colour, (self.x+label_size[1]/2, self.y+label_size[1]/2)) if size == None: self.rect = pygame.Rect(self.x, self.y, label_size[1]+label_size[0], label_size[1]*2) else: width, height = size self.rect = pygame.Rect(self.x, self.y, width, height) self.hover = False self.visible = True self.clicked = False
def make_clock(self): w = self.surface.get_width() h = self.surface.get_height() * CLOCK_FRAC font_size = int(round(h * 0.75)) font = pygame.font.SysFont('arialblack', font_size) # Compute the height of the numbers fh = font.size('0123456789')[1] surface = pygame.Surface((w, h)) surface.fill((0, 128, 255)) for hour in range(24): x = int(round(hour * w / 24.0)) x1 = int(round((hour+0.5) * w / 24.0)) pygame.draw.line(surface, (255, 255, 255), (x, 0), (x, h)) pygame.draw.line(surface, (255, 255, 255), (x1, 0), (x1, h-fh)) text = font.render(str(hour), True, (255, 255, 255)) surface.blit(text, (x1-int(round(text.get_width()/2.0)), h-fh)) self.clock = surface
def drawTextCentered(surface, text, color=grey, backgroundColor=black, font=mediumFont): # Draw the text to a new image textPic = font.render(text, True, color, backgroundColor) # Get the size of the text and the surface textW, textH = font.size(text) surfaceRect = surface.get_rect() # Calculate position for the text on the center of the surface x = surfaceRect.centerx - textW / 2 y = surfaceRect.centery - textH / 2 # Draw the text picture to the middle of the surface surface.blit(textPic, (x, y))
def _split_text(text, font, line_width, font_height, line_spacing, max_height=float('inf')): lines = [] height = 0 while text: # Determine if the row of text will be outside our area if height + font_height > max_height: break # Determine last character that fits. for i in range(len(text)): if font.size(text[:i + 1])[0] > line_width: break else: i += 1 # Adjust to last word. if i < len(text): try: # Wrap last word. line_end = text.rindex(" ", 0, i) next_start = line_end + 1 except ValueError: # Very long word overflowing line. line_end = i next_start = i else: # Remaining text shorter than line. line_end = i next_start = i # Remove this line. lines.append(text[:line_end]) text = text[next_start:] height += font_height + line_spacing return lines, text
def _pixel2index(self, pixel): font, txt, wraps = self.font, self.txt, self._wraps pixel2line = self._pixel2line l = pixel2line(pixel) if l == len(wraps) - 1: m, n = wraps[l], len(txt) else: m, n = wraps[l:l + 2] pixel_x = pixel[0] d = deque([0, 0], 2) for i in xrange(m, n): font_size_x = font.size(''.join(txt[m:i]))[0] d.append(font_size_x) if font_size_x > pixel_x: break l = [abs(font_size_x - pixel_x) for font_size_x in d] if l.index(min(l)) == 1: return i return i - 1
def showHUD(self): font = pg.font.Font(TEXT_FONT, 18) text_surface = font.render("SCORE:", True, WHITE) text_rect = text_surface.get_rect() text_width1, text_height = font.size("SCORE:") text_rect.topleft = (0, SCREEN_HEIGHT - text_height) self.screen.blit(text_surface, text_rect) text_surface = font.render(str(player.Player.score), True, RED) text_rect = text_surface.get_rect() text_width, text_height = font.size("txt") text_rect.topleft = (text_width1, SCREEN_HEIGHT - text_height) self.screen.blit(text_surface, text_rect) text_surface = font.render("Round:", True, WHITE) text_rect = text_surface.get_rect() text_width2, text_height2 = font.size("txt") text_rect.topleft = (SCREEN_WIDTH // 2 - text_width1 + 50, SCREEN_HEIGHT - text_height2) self.screen.blit(text_surface, text_rect) text_surface = font.render(str(self.Level), True, RED) text_rect = text_surface.get_rect() text_width2, text_height2 = font.size("txt") text_rect.topleft = (SCREEN_WIDTH // 2 + 50, SCREEN_HEIGHT - text_height2) self.screen.blit(text_surface, text_rect) text_surface = font.render("Lives:", True, WHITE) text_rect = text_surface.get_rect() text_width3, text_height2 = font.size("txt") text_rect.topleft = (SCREEN_WIDTH - text_width3 - 100, SCREEN_HEIGHT - text_height2) self.screen.blit(text_surface, text_rect) text_surface = font.render(str(self.NoOfLives), True, RED) text_rect = text_surface.get_rect() text_width2, text_height2 = font.size("txt") text_rect.topleft = (SCREEN_WIDTH - 45, SCREEN_HEIGHT - text_height2) self.screen.blit(text_surface, text_rect)
def getTextBounds(self, text, size): font = pygame.font.Font("arcticOS/font.ttf", size) bounds = font.size(text) return bounds
def show_dirs(screen, num_imgs, file): wait_cursor() if platform == 'win32': try: os.chdir(gl.DRIVE + ":") except: pass # Probably an OSError from not having a cd in the drive slash, get_curdir = os.sep, os.getcwd() fg_color = gl.SILVER font_size = 10 font = pygame.font.Font(gl.FONT_NAME, font_size) font.set_bold(1) # very important line = 55 name_max = 16 # dir name max menu_items = [] if get_curdir[-1] == slash: curdir = get_curdir else: curdir = get_curdir + slash paint_screen(screen, gl.BLACK) screen_height = screen.get_height() if not gl.BEEN_THERE_DONE_THAT: show_message(screen, "You can type in a directory number or shortcut (L/T/A/D/C/V/S/Q) instead of clicking: _", "bottom", 11) else: show_message(screen, "Directory number or shortcut: _", "bottom", 11) curdir_msg = check_truncate(screen.get_width(), curdir) all_files = os.listdir('.') all_files.sort() n_dirs = len([d for d in all_files if os.path.isdir(d)]) all_files = [f for f in all_files if not os.path.isdir(f)] n_files = len(all_files) all_images = get_imgs(os.getcwd(), 0) n_images = len(all_images) get_movies = lambda x, y: [i.upper().endswith(y) for i in all_images].count(True) n_movies = get_movies(all_images, ".MPG") + get_movies(all_images, ".MPEG") dirs_text = "Directories" files_text = "Files" images_text = "Images" movies_text = "MPEGs" if n_dirs == 1: dirs_text = "Directory" # unplural if n_files == 1: files_text = "File" if n_images == 1: images_text = "Image" if n_movies == 1: movies_text = "MPEG" files_msg = "[%d %s. %d %s. %d %s. %d %s]" % (n_dirs, dirs_text, n_files, files_text, n_images - n_movies, images_text, n_movies, movies_text) curdir_msg_wpos = (screen.get_width() / 2 - font.size(curdir_msg)[0] / 2) - font.size(files_msg)[0] / 2 + 10 files_msg_wpos = screen.get_width() / 2 + font.size(curdir_msg)[0] / 2 - font.size(files_msg)[0] / 2 + 20 if not gl.REFRESH_IMG_COUNT and gl.CACHE_DIR_OK: dirs = gl.CACHE_DIRS gl.REFRESH_IMG_COUNT = 1 set_caption(curdir) show_message(screen, curdir_msg, (curdir_msg_wpos, 4), 10, ("bold")) show_message(screen, files_msg, (files_msg_wpos, 4), 10) else: show_message(screen, curdir_msg, (curdir_msg_wpos, 4), 10, ("bold")) show_message(screen, files_msg, (files_msg_wpos, 4), 10) set_caption(curdir) dirs = os.listdir(curdir) dirs.sort() dirs = strip_dirs(dirs) # ensure the root dir and last dir items go at top dirs.insert(0, "..") dirs.insert(0, slash) gl.CACHE_DIRS = dirs ren_load_rect = imgv_button(screen, " (L)oad ", 0, 18, "topleft") ren_load_subdirs_rect = imgv_button(screen, " Subdirs (T)oo ", 62, 18, "topleft") if platform == 'win32': ren_drive_rect = imgv_button(screen, " Change (D)rive ", 271, 18, "topleft") dirpl_rect = imgv_button(screen, " (A)dd To Playlist ", 160, 18, "topleft") untag_all_rect = imgv_button(screen, " (C)lear Tags ", 380, 18, "topleft") view_tagged_rect = imgv_button(screen, " (V)iew Tags ", 472, 18, "topleft") filter_rect = imgv_button(screen, " (S)earch ", 559, 18, "topleft") col = 10 show_message(screen, "Right-Click directories to tag multiple directories to load. Ctrl+Left-Click to untag.", (10, 40), 10) if gl.MULT_DIRS != []: show_message(screen, "[Dirs tagged: %s]" % len(gl.MULT_DIRS), (440, 40), 10, "bold") if gl.FILTER_COMMAND != {}: show_message(screen, "[Filter: on]", (560, 40), 10, "bold") # add numbers to directory names if gl.ADDED_DIR_NUMS == 0 and dirs[0] != '*': gl.ADDED_DIR_NUMS = 1 for i, d in enumerate(dirs): dirs[i] = '*' + str(i) + gl.DIRNUMSEP + d for d in dirs: d = d[1:] # strip out the '*' marker if d[3:] == slash: if gl.DIRNUM_COLORS: dmsg = d else: ren = font.render(d, 1, gl.MSG_COLOR) else: if len(d) > name_max: if gl.DIRNUM_COLORS: dmsg = truncate_name(d, name_max) else: ren = font.render(truncate_name(d, name_max), 1, gl.MSG_COLOR) else: if gl.DIRNUM_COLORS: dmsg = d + slash else: ren = font.render(d + slash, 1, gl.MSG_COLOR) # print directory names on screen, wrapping if necessary font_height = font.size(' '.join(d.split(' ')[1:]))[1] if (line + font_height) >= (screen_height - 10): line = 55 # reset to beginning of screen col = col + (name_max + 130) # go to next column if gl.DIRNUM_COLORS: before_color = gl.MSG_COLOR if gl.MSG_COLOR == gl.SILVER: gl.MSG_COLOR = (142, 142, 142) else: gl.MSG_COLOR = gl.SILVER if before_color == gl.WHITE: ren_rect = show_message(screen, dmsg, (col, line), font_size, ("bold"), (len(dmsg[:dmsg.index(gl.DIRNUMSEP) + 1]), gl.SILVER)) else: ren_rect = show_message(screen, dmsg, (col, line), font_size, ("bold"), (len(dmsg[:dmsg.index(gl.DIRNUMSEP) + 1]), before_color)) else: ren_rect = ren.get_rect() ren_rect[0] = col ren_rect[1] = line screen.blit(ren, ren_rect) update(ren_rect) line = line + 12 menu_items.append((ren_rect, d)) if gl.DIRNUM_COLORS: gl.MSG_COLOR = before_color normal_cursor() pygame.event.set_blocked(MOUSEMOTION) while 1: event = pygame.event.poll() pygame.time.wait(1) cursor = pygame.mouse.get_pos() (esc_rect, close_font) = close_button(screen) hover_fx(screen, curdir, menu_items, cursor) if platform == 'win32':# hover_cursor(cursor, [ren_load_rect, ren_load_subdirs_rect, ren_drive_rect, dirpl_rect, untag_all_rect, view_tagged_rect, filter_rect, esc_rect] + [x[0] for x in menu_items]) hover_button(ren_load_rect, cursor, screen, " (L)oad ", 0, 18, "topleft") hover_button(ren_load_subdirs_rect, cursor, screen, " Subdirs (T)oo ", 62, 18, "topleft") if platform == 'win32': hover_button(ren_drive_rect, cursor, screen, " Change (D)rive ", 271, 18, "topleft") hover_button(dirpl_rect, cursor, screen, " (A)dd To Playlist ", 160, 18, "topleft") hover_button(untag_all_rect, cursor, screen, " (C)lear Tags ", 380, 18, "topleft") hover_button(view_tagged_rect, cursor, screen, " (V)iew Tags ", 472, 18, "topleft") hover_button(filter_rect, cursor, screen, " (S)earch ", 559, 18, "topleft") if left_click(event): for item in menu_items: if item[0].collidepoint(cursor): if pygame.mouse.get_pressed()[0] and (pygame.key.get_pressed()[K_LCTRL] or\ pygame.key.get_pressed()[K_RCTRL]): try: # untag directory gl.MULT_DIRS.remove(os.getcwd() + slash + ' '.join(item[1].split(' ')[1:])) show_message(screen, " " * 30, (440, 40), 10, ("bold")) show_message(screen, "[Dirs tagged: %s]" % len(gl.MULT_DIRS), (440, 40), 10, "bold") except: pass else: # (normal mode) change to a single directory and load its images (num_imgs, file) = do_change_dir(screen, num_imgs, file, item[1]) return (num_imgs, file) if right_click(event): for item in menu_items: if item[0].collidepoint(cursor): # tag directory if os.getcwd()[-1] != slash: gl.MULT_DIRS.append(os.getcwd() + slash + ' '.join(item[1].split(' ')[1:])) else: gl.MULT_DIRS.append(os.getcwd() + ' '.join(item[1].split(' ')[1:])) show_message(screen, " " * 30, (440, 40), 10, ("bold")) show_message(screen, "[Dirs tagged: %s]" % len(gl.MULT_DIRS), (440, 40), 10, "bold") # allow number keys to be used to change directories dirnum = None if event.type == KEYDOWN and event.key in (K_1, K_2, K_3, K_4, K_5, K_6, K_7, K_8, K_9, K_0, K_KP1, K_KP2, K_KP3, K_KP4, K_KP5, K_KP6, K_KP7, K_KP8, K_KP9, K_KP0): dirnum = get_dirnum(screen, event.key) if dirnum != 'backspaced': for item in menu_items: if item[1].startswith(str(dirnum)): (num_imgs, file) = do_change_dir(screen, num_imgs, file, item[1]) return (num_imgs, file) break if hit_key(event, K_RETURN) or hit_key(event, K_SPACE) or hit_key(event, K_l): (num_imgs, file) = do_load_dir() break if hit_key(event, K_t): # load subdirs on keypress 't' (num_imgs, file) = do_subdirs_too() break if hit_key(event, K_s): # search command_get_filter_info(screen) (num_imgs, file) = show_dirs(screen, num_imgs, file) break if hit_key(event, K_d): # change drives if platform == 'win32': gl.WAS_IN_CHANGE_DRIVES = 1 (num_imgs, file) = do_change_drive(screen, num_imgs, file) gl.WAS_IN_CHANGE_DRIVES = 0 break if hit_key(event, K_c): # clear tag list do_untag(screen) if hit_key(event, K_v): # view tagged dirs do_view_tagged(screen, num_imgs, file) break # break main loop to display properly if hit_key(event, K_a): # add curdir to playlist command_add_to_play_list(screen, curdir) return (num_imgs, file) if hit_key(event, K_ESCAPE): gl.ESCAPED = 1 gl.ADDED_DIR_NUMS = 0 break if left_click(event): if esc_rect.collidepoint(cursor): gl.ESCAPED = 1 gl.ADDED_DIR_NUMS = 0 break if ren_load_rect.collidepoint(cursor): # load current dir (num_imgs, file) = do_load_dir() break if ren_load_subdirs_rect.collidepoint(cursor): # load subdirs too (num_imgs, file) = do_subdirs_too() break if platform == 'win32': if ren_drive_rect.collidepoint(cursor): gl.WAS_IN_CHANGE_DRIVES = 1 (num_imgs, file) = do_change_drive(screen, num_imgs, file) gl.WAS_IN_CHANGE_DRIVES = 0 break if dirpl_rect.collidepoint(cursor): command_add_to_play_list(screen, curdir) return (num_imgs, file) if untag_all_rect.collidepoint(cursor): do_untag(screen) if view_tagged_rect.collidepoint(cursor): do_view_tagged(screen, num_imgs, file) break # break main loop to display properly if filter_rect.collidepoint(cursor): command_get_filter_info(screen) (num_imgs, file) = show_dirs(screen, num_imgs, file) break check_quit(event) gl.CACHE_DIR_OK = 1 return (num_imgs, file)
def input(self, event): """ accept a user KEYDOWN event and add the text associated with the keypress to the editor image event-- a user KEYDOWN event return None """ k, font, lines = self._cursor, self.font, self._lines rect_w, txt, wraps = self.rect.w, self.txt, self._wraps image, bkg_img = self.image, self._image draw_line, index2line = self._draw_line, self._index2line pixel2index, update = self._pixel2index, self._update Line = _Line if event.type == KEYDOWN: l = index2line(k) # handle cursor navigation if event.key in DIRECTION_KEYS: draw_line(l) #to clear the cursor? if event.key == K_UP: if l > 0: pixel = (font.size(''.join(txt[wraps[l]:k]))[0], lines[l - 1].rect.y) self._cursor = pixel2index(pixel) else: self._cursor = 0 elif event.key == K_DOWN: if (len(wraps) - 1) > l: pixel = (font.size(''.join(txt[wraps[l]:k]))[0], lines[l + 1].rect.y) self._cursor = pixel2index(pixel) else: self._cursor = len(txt) - 1 elif event.key == K_LEFT: self._cursor -= 1 if self._cursor < 0: self._cursor = 0 elif event.key == K_RIGHT: self._cursor += 1 if self._cursor > (len(txt) - 1): self._cursor = len(txt) - 1 # handle newlines elif event.key == K_RETURN: txt.insert(k, '\n') self._cursor += 1 lines.insert(l + 1, Line(Surface((0, 0)), Rect(0, 0, 0, 0))) update(l) # handle backspaces elif event.key == K_BACKSPACE: if k == 0: pass else: lines[l].clear(image, bkg_img) self._cursor -= 1 k = self._cursor char = txt.pop(k) # if l> index2line(k) then the line no longer exists if l > index2line(k): del lines[l] if l == 0: update(l) else: update(l - 1) # handle ascii input else: if event.unicode: txt.insert(k, event.unicode.encode("ascii")) self._cursor += 1 if k == wraps[l]: # wrapped to a new line if l == 0: update(l) # update line else: update(l - 1) # else: update from previous line else: update(l)
def main(): font_path = "data/talldark.ttf" fullscreen = True video_flags = fullscreen and FULLSCREEN print video_flags pygame.init() # get the highest resolution resolution = pygame.display.list_modes()[0] # create our main window SDL surface surface = pygame.display.set_mode(resolution, video_flags) pygame.display.set_caption("Stopwatch -- stopwatch.alej0.tk") # get highest font size that fits resolution width font_size = int(resolution[1] / 1.2) font_size_fits = False max_string_length = resolution[0] / 8 * 7 while not font_size_fits: font = pygame.font.Font(font_path, font_size) font_rect = font.size("00:00:00,00") if font_rect[0] > max_string_length: font_size = font_size - 10 else: font_size_fits = True # get the point to draw the font in the midle of the screen font_blit_point = resolution[0] / 16, resolution[1] / 2 - font_rect[1] / 2 on = False #wheter the stopwatch is running or not a = 0 # milliseconds from start start_tick = 0 # the number of ticks when we began counting while True: event = pygame.event.poll() if event.type == KEYUP: if event.key == K_ESCAPE: break if event.key == K_SPACE: if not on: # starting the timer, so set the tick count reference to the current tick count # plus the last tick count start_tick = pygame.time.get_ticks() - a # swap value on = not on elif event.key == K_r: # initialize the tick count a = 0 on = False elif event.key == K_f: # swap video mode widowed, fullscreen fullscreen = not fullscreen video_flags = (fullscreen and FULLSCREEN) | (not fullscreen and RESIZABLE) pygame.display.set_mode(resolution, video_flags) if on: # get the amount of ticks(milliseconds) that passed from the start a = (pygame.time.get_ticks() - start_tick) # render the time, by converting ticks to datetime.time + hundredth of a second t = time((a / 1000) / 3600, ((a / 1000) / 60 % 60), (a / 1000) % 60) h_o_s = str(a)[-3:][:2] # hundredth of a second t_string = ','.join((t.strftime("%H:%M:%S"), h_o_s)) tempsurface = font.render(t_string, 1, THECOLORS["black"]) surface.fill(THECOLORS["white"]) #fill the screen with white, to erase the previous time surface.blit(tempsurface, font_blit_point) # draw the time pygame.display.flip() pygame.time.wait(100)
def render_textrect(string, font, rect, text_color, background_color, justification=0): final_lines = [] requested_lines = string.splitlines() # Create a series of lines that will fit on the provided # rectangle. for requested_line in requested_lines: if font.size(requested_line)[0] > rect.width: words = requested_line.split(' ') # if any of our words are too long to fit, return. for word in words: if font.size(word)[0] >= rect.width: raise ("The word " + word + " is too long to fit in the rect passed.") # Start a new line accumulated_line = "" for word in words: test_line = accumulated_line + word + " " # Build the line while the words fit. if font.size(test_line)[0] < rect.width: accumulated_line = test_line else: final_lines.append(accumulated_line) accumulated_line = word + " " final_lines.append(accumulated_line) else: final_lines.append(requested_line) # Let's try to write the text out on the surface. surface = pygame.Surface(rect.size) surface.fill(background_color) accumulated_height = 0 for line in final_lines: if accumulated_height + font.size(line)[1] >= rect.height: raise "Once word-wrapped, the text string was too tall to fit in the rect." if line != "": tempsurface = font.render(line, 1, text_color) if justification == 0: surface.blit(tempsurface, (0, accumulated_height)) elif justification == 1: surface.blit(tempsurface, ((rect.width - tempsurface.get_width()) / 2, accumulated_height)) elif justification == 2: surface.blit( tempsurface, (rect.width - tempsurface.get_width(), accumulated_height)) else: raise ("Invalid justification argument: " + str(justification)) accumulated_height += font.size(line)[1] return surface
def centerText(font, text, window): sz = font.size(text) return window[0] / 2 - sz[0] / 2, window[1] / 2 - sz[1] / 2
def font_height(font): w, h = font.size("X") return h
def size(self, text): return font.size(text)
import pygame
def screen(self, surface, pos, fgcolor=(128, 128, 125), font=None, interline=0): fgcolor = [fgcolor] px, y = pos mono = True if not font: font = Text.defaultfont if font.size('i') != font.size('x'): mono = False char_w, char_h = font.size(' ') char_h += interline style_cmd = { '+': True, '-': False, 'b': font.set_bold, 'i': font.set_italic, 'u': font.set_underline } bz = self.baliz def set_style(pos): while True: if bz and pos == bz[0][0]: _, mode, style, color, value = bz.pop(0) if mode: style_cmd[style](style_cmd[mode]) elif color: if value: fgcolor.append(Color(int(value, 16) << 8)) else: fgcolor.pop() else: break rec = Rect(pos, (0, 0)) pos = 0 set_style(pos) if mono: for lines in self: for line in lines: x = px for char in line: rec = rec.unionall([ (surface.blit(font.render(char, 1, fgcolor[-1]), (x, y))), rec ]) x += char_w pos += 1 set_style(pos) y += char_h pos += 1 set_style(pos) return rec for lines in self: for line in lines: x = px for char in line: x = surface.blit(font.render(char, 1, fgcolor[-1]), (x, y)) rec = rec.unionall([x, rec]) x = x.right pos += 1 set_style(pos) y += char_h pos += 1 set_style(pos) return rec
def help(screen): paint_screen(screen, gl.BLACK) (screen_width, screen_height) = (screen.get_width(), screen.get_height()) (esc_rect, font) = close_button(screen) show_message(screen, "Main Keyboard Commands", "top", 11, ("bold", "underline", "transparent")) key_list = [" Space/N/Ctrl+Tab=Next image, Backspace/B=Previous Image. Ctrl+B=Toggle Image Border ", " D=Change Directory ", " I=Image Browser ", " T=Thumbnails (Space/N/Right-Click=Next. Backspace/B/Middle-Click=Prev. P/Pause=Pause), Ctrl+T=Transparent font ", " 4=View four images at a time (Space/N/Right-Click=Next. Backspace/B/Middle-Click=Previous. W=Slideshow) ", " W=Slideshow (Space=Skip forward. Backspace=Skip backward. P/Pause=Pause) ", " P=Add to Playlist, Ctrl+P=Playlist Options ", " C=Close Menu ", " F=First Image (Jump to the first image), L=Last Image (Jump to the last image), Ctrl+L=Lock Zoom ", " '+'=Zoom In. '-'=Zoom Out. Ctrl+'+'=Zoom In (Double). Ctrl+'-'=Zoom Out (Double). Ctrl+Alt+'+'=Zoom In (Scale2X) ", " R=Rotate Right. Ctrl+R=Rotate Left ", " Escape=Refresh (Reverts images to original state or reloads after directory changes) ", " M=Flip Horizontal (Mirror), V=Flip Vertical ", " S=Shuffle, U=Unshuffle ", " A=Download Image (Saves remote images to your imgv download directory) ", " Delete/Ctrl+W=Close Image, Ctrl+Delete=Permanently delete image from harddisk", " X=Hide Image, Ctrl+X=Toggle displaying the main and on-the-fly-Exif status bars ", " O=Open URL to extract images from a Website ", " F1=Help, F2=640x480, F3=800x600, F4=1024x768, F5=1280x1024, F6/Alt+Enter=Fullscreen, F7=Resize Options ", " H=Hand Tool (Allows you to pan/move images on the screen) ", " Q=Exit imgv at any time (except when prompted for input) ", " Arrow keys=Scroll the image left/right/up/down. PgUp/PgDown/Home/End=full up/full down/full left/full right, (Mouse Wheel=up/down) ", " E=Edit ", " Z=Image Properties ", " 1=Toggle scaling large images to fit the window ", " Ctrl+Zero=Fit image to the window, Alt+Zero=Actual Size (Show image at its real size) "] key_list.sort() if screen_width == 640: linesep = 13 font_size = 9 else: linesep =15 font_size = 11 pos = linesep for line in key_list: show_message(screen, line, (2, pos), font_size, ("transparent")) pos += linesep mouse_msg = "Main Mouse Commands" show_message(screen, mouse_msg, ((screen_width / 2) - (font.size(mouse_msg)[0] / 2), pos, 0, 0), 11, ("bold", "underline", "transparent")) mouse_list = [" Left-Click=Select menu options/Load images in Four at a Time, Thumbnail and Image browser/Click buttons and links/Change directories ", " Right-Click=Open or move the main menu/Go forward a page in Four at a Time, Thumbnail and Image Browser/Tag directories ", " Middle-Click=Close the main menu/Go back a page in Four at a Time, Thumbnail and Image Browser ", " Mouse Scroll Wheel=Scroll images that are larger than the screen up or down/Activate the Hand Tool "] pos += linesep for line in mouse_list: show_message(screen, line, (2, pos), font_size, ("transparent")) pos += linesep gl.MSG_COLOR = gl.BLUE doc_msg = "View imgv's online documentation" doc_rect = show_message(screen, doc_msg, ((screen_width / 2) - (font.size(doc_msg)[0] / 2), screen_height - 20, 0, 0), 12, ("underline", "bold")) donate_msg = "Donate!" donate_rect = show_message(screen, donate_msg, ((screen_width) - (font.size(donate_msg)[0] + 70), screen_height - 35, 0, 0), 12, ("bold", "underline")) gl.MSG_COLOR = gl.SILVER author_msg = "Author: Ryan Kulla" show_message(screen, author_msg, ((screen_width) - (font.size(author_msg)[0] - 10), screen_height - 15, 0, 0), 9, ("bold", "transparent"), (7, gl.WHITE)) normal_cursor() print_version(screen, screen_height) pygame.event.set_blocked(MOUSEMOTION) while 1: event = pygame.event.poll() pygame.time.wait(1) cursor = pygame.mouse.get_pos() check_quit(event) hover_cursor(cursor, (doc_rect, esc_rect, donate_rect)) if hit_key(event, K_ESCAPE) or hit_key(event, K_SPACE): gl.ESCAPED = 1 gl.MSG_COLOR = gl.MENU_COLOR break if left_click(event): wait_cursor() if doc_rect.collidepoint(cursor): webbrowser.open("http://imgv.sourceforge.net/doc/", 1, 1) if donate_rect.collidepoint(cursor): webbrowser.open("http://imgv.sourceforge.net/donate.html", 1, 1) elif esc_rect.collidepoint(cursor): gl.ESCAPED = 1 gl.MSG_COLOR = gl.MENU_COLOR break
def getTextSize(self, text, font = None): if not font: font = getTheme().defaultFont return font.size(text)
def show_thumbs(screen, SPACER, x, i, j, place, marker, font, font_size): # show thumbnails with correct aspect ratio if place < len(gl.files): img_name = gl.files[place] img = load_img(img_name, 0) (img_width, img_height) = img.get_size() splitval = None if gl.THUMB_VAL.find("x") != -1: splitval = "x" elif gl.THUMB_VAL.find("X") != -1: splitval = "X" if splitval != None: (square_width, square_height) = int(gl.THUMB_VAL.split(splitval)[0]), int(gl.THUMB_VAL.split(splitval)[1]) small_img = img if img_width > img_height: if ( (not img_width < square_width and not img_height < square_height) or (img_width > square_width) or (img_height > square_height) or (img_width > square_width and img_height > square_height) ): r = float(img_width) / float(img_height) new_width = square_width new_height = int(new_width / r) scale_val = new_width, new_height if scale_val[0] > square_width or scale_val[1] > square_height: scale_val = int(new_width / 1.32), int(new_height / 1.32) if scale_val[0] > square_width or scale_val[1] > square_height: if square_width >= 200 or square_height >= 200: scale_val = int(scale_val[0] / 2), int(scale_val[1] / 2) small_img = pygame.transform.scale(img, scale_val) if img_width < img_height: if ( (not img_width < square_width and not img_height < square_height) or (img_width > square_width) or (img_height > square_height) or (img_width > square_width and img_height > square_height) ): r = float(img_height) / float(img_width) new_height = square_height new_width = int(new_height / r) scale_val = new_width, new_height if scale_val[0] > square_width or scale_val[1] > square_height: scale_val = int(new_width / 2), int(new_height / 2) else: scale_val = new_width, new_height small_img = pygame.transform.scale(img, scale_val) if img_width == img_height: if ( (not img_width < square_width and not img_height < square_height) or (img_width > square_width) or (img_height > square_height) or (img_width > square_width and img_height > square_height) ): r = float(img_width) / float(img_height) new_height = square_height new_width = square_width scale_val = new_width, new_height small_img = pygame.transform.scale(img, scale_val) (img_width, img_height) = small_img.get_size() if (i + square_width) >= screen.get_width(): i = SPACER j = j + (square_height + SPACER) if (j + square_height) >= screen.get_height(): i, j = SPACER, SPACER gl.MAX_THUMBS = marker # figure out how many thumbs fit on a page set_caption("imgv") if not gl.MAX_THUMBS_SET: gl.MAX_THUMBS_SET = gl.MAX_THUMBS return (x, i, j, place, 1, marker) # draw individual thumbnail backgrounds: paint_screen(gl.THUMB_BG_COLOR_VAL, (i, j, square_width, square_height)) if gl.THUMB_BORDER_VAL: # draw borders: left_line = line(screen, gl.THUMB_BORDER_COLOR, (i - 1, j - 1), (i - 1, square_height + j)) right_line = line( screen, gl.THUMB_BORDER_COLOR, (i + square_width, j), (i + square_width, square_height + j) ) top_line = line(screen, gl.THUMB_BORDER_COLOR, (i, j - 1), ((i + square_width), j - 1)) bottom_line = line( screen, gl.THUMB_BORDER_COLOR, (i, square_height + j), ((i + square_width), square_height + j) ) update(left_line), update(top_line), update(right_line), update(bottom_line) thumb_name = check_truncate(square_width, basename(img_name)) wpos = i + ((square_width / 2) - (font.size(thumb_name)[0] / 2)) small_img_rect = small_img.get_rect() small_img_rect[0] = i small_img_rect[1] = j x.append((small_img_rect, img_name)) screen.blit(small_img, (i, j)) update(small_img_rect) i = i + (square_width + SPACER) place = place + 1 marker = marker + 1 if gl.THUMB_STATUS_BARS: # display thumbnail's filename: show_message(thumb_name, (wpos, j + square_height - 12), font_size, ("bold")) if place >= len(gl.files): return (x, 0, 0, place, 1, marker) return (x, i, j, place, 0, marker)
line_spacing = 2 img = cam.get_image() img = pygame.transform.scale(img, dim) if 'pisettings' in sys.modules: if "rotateangle" in pisettings: img = pygame.transform.rotate(img, pisettings["rotateangle"]) elapsed = (datetime.now() - to_display[1]).seconds if elapsed < DISPLAY_LENGTH: lines = wrap_text(to_display[0], img.get_width()) for line in lines: label = font.render(line, 0, font_color, (0, 0, 0)) label.set_alpha((1 - elapsed / DISPLAY_LENGTH) * 255) img.blit(label, (PADDING_X, y)) y += font.size(line)[1] + line_spacing # flash color indicating successful scan if was_scanned: pygame.draw.rect(img, (0, 0, 255), (0, 0, dim[0], dim[1]), 0) was_scanned = False display.blit(img, (0, 0)) pygame.display.flip() # q to quit for event in pygame.event.get(): if event.type == KEYDOWN and event.key == K_q: capture = False # don't scan every frame
def prefs_index_fx(screen, it, font, msg): gl.NOT_HOVERED = 0 fxpos = (it[0][0] - 10, it[0][1] + (font.size(it[1])[1] / 2) - 13, it[0][2], it[0][3]) show_message(".", fxpos, 16, ("bold", "transparent")) show_message("%s%s%s" % (" " * 100, msg, " " * 100), "bottom", 12, ("transparent")) return fxpos