def paint_arrow(self, xl, xr, y, arrow_type, left): if arrow_type == "menu_entry": fgcolor = self.unselected_color elif arrow_type == "menu_entry_selected": fgcolor = self.selected_color elif arrow_type == "menu_entry_activated": fgcolor = (1.0 - self.selected_color[0], 1.0 - self.selected_color[1], 1.0 - self.selected_color[2], self.selected_color[3]) else: return fo = cairo.FontOptions() fo.set_antialias(cairo.ANTIALIAS_NONE) self.cr.set_font_options(fo) self.cr.set_antialias(cairo.ANTIALIAS_NONE) x = (xl + xr) / 2.0 h = (self.cached_menu_size / 2.0) - 1.0 self.cr.set_source_rgba(fgcolor[0], fgcolor[1], fgcolor[2], fgcolor[3]) self.cr.move_to(x, y - h) if (left): self.cr.line_to(x - self.cached_menu_size + 2, y) else: self.cr.line_to(x + self.cached_menu_size - 2, y) self.cr.line_to(x, y + h) self.cr.line_to(x, y - h) self.cr.fill() fo = cairo.FontOptions() fo.set_antialias(cairo.ANTIALIAS_DEFAULT) self.cr.set_font_options(fo) self.cr.set_antialias(cairo.ANTIALIAS_DEFAULT)
def _generate_surface(self): bpp = 4 #if self._format == cairo.FORMAT_RGB32: # bpp = 3 self._data = array.array('c', chr(0) * self.width * self.height * bpp) stride = self.width * bpp self.surface = cairo.ImageSurface.create_for_data( self._data, self._format, self.width, self.height, stride) self._texture = glGenTextures(1) self.cr = cairo.Context(self.surface) self.pango = pangocairo.CairoContext(self.cr) self.layout = self.pango.create_layout() # force subpixel rendering self.font_options = cairo.FontOptions() self.font_options.set_antialias(cairo.ANTIALIAS_SUBPIXEL) self.cr.set_font_options(self.font_options) glBindTexture(GL_TEXTURE_2D, self._texture) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, self._filter) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, self._filter) self.invalidate()
def set_image_from_text(self, button, text, font_family="Georgia", font_size=12, font_slant=cairo.FONT_SLANT_NORMAL, font_weight=cairo.FONT_WEIGHT_NORMAL, border=False, line_padding=3, antialiasing=cairo.ANTIALIAS_DEFAULT): data = array.array('B', [0] * 2048) stride = cairo.ImageSurface.format_stride_for_width(cairo.FORMAT_A8, ICON_WIDTH) image = cairo.ImageSurface.create_for_data(data, cairo.FORMAT_A8, ICON_WIDTH, ICON_HEIGHT, stride) cr = cairo.Context(image) cr.set_source_rgba(1.0, 1.0, 1.0, 255.0) cr.select_font_face(font_family, font_slant, font_weight) cr.set_font_size(font_size) fo = cairo.FontOptions() fo.set_antialias(antialiasing) cr.set_font_options(fo) lines = text.split('\n') for y, line in enumerate(lines): x_bearing, y_bearing, width, height = cr.text_extents(line)[:4] #cr.move_to(0.5 - ICON_WIDTH / 2 - x_bearing, 0.5 - ICON_HEIGHT / 2 - y_bearing) cr.move_to(ICON_WIDTH / 2 - width / 2, ICON_HEIGHT / 2 + height / 2 + y*(height+line_padding) - (height/1.5)*(len(lines)-1)) cr.show_text(line) if border: cr.move_to(0,0) cr.line_to(64,0) cr.line_to(64,32) cr.line_to(0,32) cr.line_to(0,0) cr.stroke() self.set_image(button, data)
def paint_pattern(self, cr, x, y, antialias, label="", background=WHITE, foreground=BLACK): w, h = self.get_size() bw = w//4 bh = h//4 FONT_SIZE = w//8 cr.set_operator(cairo.OPERATOR_SOURCE) cr.set_source_rgb(*background) cr.rectangle(x*bw, y*bh, bw, bh) cr.fill() fo = cairo.FontOptions() fo.set_antialias(antialias) cr.set_font_options(fo) cr.set_antialias(antialias) cr.set_source_rgb(*foreground) cr.set_font_size(FONT_SIZE) cr.move_to(x*bw+bw//2-FONT_SIZE//2, y*bh+bh//2+FONT_SIZE//3) cr.show_text(PATTERN) cr.stroke() if label: cr.set_font_size(15) cr.move_to(x*bw+bw//2-FONT_SIZE//2, y*bh+bh*3//4+FONT_SIZE//3) cr.show_text(ANTIALIAS[antialias]) cr.stroke()
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): # docstring inherited # Note: (x, y) are device/display coords, not user-coords, unlike other # draw_* methods if ismath: self._draw_mathtext(gc, x, y, s, prop, angle) else: ctx = gc.ctx ctx.new_path() ctx.move_to(x, y) ctx.save() ctx.select_font_face(*_cairo_font_args_from_font_prop(prop)) ctx.set_font_size(prop.get_size_in_points() * self.dpi / 72) opts = cairo.FontOptions() opts.set_antialias( cairo.ANTIALIAS_DEFAULT if mpl.rcParams["text.antialiased"] else cairo.ANTIALIAS_NONE) ctx.set_font_options(opts) if angle: ctx.rotate(np.deg2rad(-angle)) ctx.show_text(s) ctx.restore()
def render_labels(self, labels, color_rgba=None): surface = self.get_surface() if self.canvas is None or not hasattr(self.canvas, 'df_shape_centers'): # Canvas is not initialized, so return empty cairo surface. return surface cairo_context = cairo.Context(surface) color_rgba = (1, 1, 1, 1) if color_rgba is None else color_rgba if not isinstance(color_rgba, pd.Series): shape_rgba_colors = pd.Series( [color_rgba], index=self.canvas.df_shape_centers.index) else: shape_rgba_colors = color_rgba font_options = cairo.FontOptions() font_options.set_antialias(cairo.ANTIALIAS_SUBPIXEL) cairo_context.set_font_options(font_options) for shape_id, label_i in labels.iteritems(): cairo_context.set_source_rgba(*shape_rgba_colors.ix[shape_id]) self.render_label(cairo_context, shape_id, label_i, label_scale=0.6) return surface
def render(self, text): """Render a text string. text: Render this text Returns a 2-dimensional array indexed [height,width]. The width is dynamic and chosen such that the text fits exactly. The values represent grayscales. """ if len(text) < 1: return numpy.zeros([self.height, self.width], self._TYPE) width = len(text) * self.height * 2 data = numpy.zeros([self.height, width], self._TYPE) surface = cairo.ImageSurface.create_for_data(data, self._FORMAT, width, self.height) c = cairo.Context(surface) c.set_source_rgba(1, 1, 1, 0) c.paint() c.set_source_rgba(0, 0, 0, 1) c.select_font_face(self._chooseFont(), cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) # The slight horizontal scaling compensates for the non-square pixels. # The font matrix can set the size but *else* is ineffective with bitmap fonts. c.set_font_matrix(cairo.Matrix(self.fontsize*1.2, 0, 0, self.fontsize, 0, 0)) c.set_font_options(cairo.FontOptions(cairo.HINT_METRICS_ON, cairo.HINT_STYLE_FULL)) fascent, fdescent, fheight, fxadvance, fyadvance = c.font_extents() xbearing, ybearing, awidth, aheight, xadvance, yadvance = c.text_extents(text) c.move_to(xbearing, self.height-fdescent) c.show_text(text) surface.flush() return data[:,0:int(xadvance+xbearing)]
def _build_csf(self): "Builds and caches a Cairo Scaled Font." fontFace = cr.ToyFontFace(self.name) identityMatrix = cr.Matrix() fontOptions = cr.FontOptions() # get defaults scaling = self.size * self._gschemScalingConstant scalingMatrix = cr.Matrix(xx = scaling, yy = scaling) self._csf = cr.ScaledFont(fontFace, scalingMatrix, identityMatrix, fontOptions)
def main(): if len(sys.argv) != 3: usage() sys.exit(1) version = sys.argv[1] imgpath = sys.argv[2] surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 140,24) ctx = cairo.Context(surface) c = pangocairo.CairoContext(ctx) l = c.create_layout() font_desc = pango.FontDescription('Grixel Acme 7 Wide Bold 14') l.set_font_description(font_desc) fo = cairo.FontOptions() fo.set_antialias(cairo.ANTIALIAS_NONE) c.set_font_options(fo) pangocairo.context_set_font_options (l.get_context(), fo) l.set_text('theory') set_context_color(ctx,'#333333') ctx.move_to(4,-8) c.show_layout(l) c.update_layout(l) l = c.create_layout() font_desc = pango.FontDescription('Grixel Acme 7 Wide 7') attr = pango.AttrList() attr.insert(pango.AttrLetterSpacing(1200,0,100)) l.set_attributes(attr) l.set_font_description(font_desc) fo = cairo.FontOptions() fo.set_antialias(cairo.ANTIALIAS_NONE) pangocairo.context_set_font_options (l.get_context(), fo) l.set_text(version) ctx.move_to(105,8) ctx.set_source_rgb (.33,.33,.33) c.show_layout(l) c.update_layout(l) surface.write_to_png(imgpath)
def create_pango_context(self): pango_context = self.pango_fontmap.create_context() options = cairo.FontOptions() options.set_hint_metrics(cairo.HINT_METRICS_OFF) pangocairo.context_set_font_options(pango_context, options) pangocairo.context_set_resolution(pango_context, 72) return pango_context
def createScaledFont(family, size, slant=cairo.FONT_SLANT_NORMAL, weight=cairo.FONT_WEIGHT_NORMAL): """ Simple helper function to create a cairo ScaledFont. """ face = cairo.ToyFontFace(family, slant, weight) DEFAULT_FONT_OPTIONS = cairo.FontOptions() DEFAULT_FONT_OPTIONS.set_antialias(cairo.ANTIALIAS_SUBPIXEL) return cairo.ScaledFont(face, cairo.Matrix(xx=size, yy=size), cairo.Matrix(), DEFAULT_FONT_OPTIONS)
def test_cairo_font_options(self): window = Gtk.Window() if Gtk._version == "4.0": window.set_font_options(cairo.FontOptions()) font_opts = window.get_font_options() else: screen = window.get_screen() font_opts = screen.get_font_options() assert font_opts is not None self.assertTrue(isinstance(font_opts.get_subpixel_order(), int))
def np_text(self, text, fontname='times', fontsize=48.0, angle=0): ''' Generate an text within an array :Parameters: `text` : str Text to be generated `fontname` : str Font family name `fontsize` : int Font size `angle` : float Text angle ''' # Dummy surface to get text extents surface = cairo.ImageSurface(cairo.FORMAT_A8, 1, 1) ctx = cairo.Context(surface) ctx.set_font_size(fontsize) (x, y, w, h, dx, dy) = ctx.text_extents( text ) # 6 element tupple - (x_bearing, y_bearing, width, height, x_advance, y_advance) size = ( int(np.sqrt(w**2 + h**2) + 1) // 4 ) * 4 + 4 # ** = power symbol. 2**3 is 2^3. // is integer division # Actual surface surface = cairo.ImageSurface(cairo.FORMAT_A8, size, size) #over-write old surface ctx = cairo.Context(surface) #over-write old ctx options = cairo.FontOptions( ) #creates a FontOptions object with defualt values options.set_antialias(cairo.ANTIALIAS_SUBPIXEL) options.set_hint_style(cairo.HINT_STYLE_FULL) ctx.set_font_options( options) #use the defualt font options values from above ctx.set_source_rgba(0, 0, 0, 0) ctx.paint() #paint blank canvas, essentially ctx.set_source_rgba(1, 1, 1, 1) #change color to white and opaque ctx.select_font_face(fontname) #make font 'sans' ctx.set_font_size(fontsize) ctx.move_to( size // 2, size // 2) #from strange math above ((int(np.sqrt(w**2+h**2)+1)//4)*4+4 ) ctx.rotate(angle) ctx.rel_move_to(-w // 2, h // 2) ctx.show_text(text) #draw text on surface # Make an array oput of surface buf = surface.get_data() #raw binary data representing the surface Z = np.frombuffer( buf, np.uint8) # Interpret a buffer as a 1-dimensional array. Z.shape = ( size, size, 1 ) # shape the buffer to the size of the surface in pixels. the array is the values for each pixel from 0-255. empty space is represented by 0 return self.np_crop(Z, 0) # jump to crop method!
def __on_start_training(self, widget): self.lock_widgets(True) # Initialize the cairo surface and relative context surface = cairo.ImageSurface(cairo.FORMAT_RGB24, IMG_PIXELS, IMG_PIXELS) ctx = cairo.Context(surface) # Disable antialias for font rendering fo = cairo.FontOptions() fo.set_antialias(cairo.ANTIALIAS_NONE) fo.set_hint_style(cairo.HINT_STYLE_NONE) ctx.set_font_options(fo) train_dict = defaultdict(list) for fntbtn in self.fonts.foreach(): font = fntbtn.get_font_name() # Select new font face ctx.select_font_face(font, cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) ctx.set_font_size(IMG_PIXELS) for char in self.get_alphabet(): ctx.set_source_rgb(1, 1, 1) ctx.rectangle(0, 0, IMG_PIXELS, IMG_PIXELS) ctx.fill() ctx.set_source_rgb(0, 0, 0) x_bearing, y_bearing, width, height = ctx.text_extents( char)[:4] fx = IMG_PIXELS / 2 fy = IMG_PIXELS / 2 fx = fx - width / 2 - x_bearing fy = fy - height / 2 - y_bearing ctx.move_to(fx, fy) ctx.show_text(char) train_dict[char].append(scaled_from_rawdata( surface.get_data())) #if DEBUG: # surface.write_to_png("images/" + str(ord(char)) + ".png") self.thread = Thread(target=self.__on_train, args=(train_dict, )) self.thread.setDaemon(True) self.thread.start() gobject.timeout_add(500, self.__update_percentage)
def text_block(ctx, obj, text, font, lang="en-US", debug=False): ctx.save() lyt = PangoCairo.create_layout(ctx) pg_ctx = lyt.get_context() pg_ctx.set_language(Pango.Language.from_string(lang)) fo = cairo.FontOptions() fo.set_antialias(cairo.ANTIALIAS_SUBPIXEL) PangoCairo.context_set_font_options(pg_ctx, fo) font_family = font.family if not font.replace else font.replace pg_font = Pango.FontDescription("{} {}px".format(font_family, font.size)) lyt.set_font_description(pg_font) lyt.set_markup(text, -1) # force length calculation lyt.set_height(obj.height * Pango.SCALE * 1.5) # TODO what? lyt.set_width(obj.width * Pango.SCALE) lyt.set_alignment(Pango.Alignment.CENTER) #PangoCairo.update_layout(ctx, lyt) pg_size = lyt.get_pixel_size() ink, logical = lyt.get_pixel_extents() while ink.height > obj.height and pg_font.get_size() > 0: pg_font.set_size(pg_font.get_size() - Pango.SCALE) lyt.set_font_description(pg_font) ink, logical = lyt.get_pixel_extents() #x = obj["x"] - pext.x - pext.width / 2 #y = obj["y"] - pext.y - pext.height / 2 x = (obj.x + obj.width / 2) - ((ink.x + ink.width / 2)) y = (obj.y + obj.height / 2) - ((ink.y + ink.height / 2)) #x = obj["x"] #y = obj["y"] if debug: print("x,y: %s, %s" % (x, y)) ctx.translate(x, y) PangoCairo.update_layout(ctx, lyt) PangoCairo.layout_path(ctx, lyt) ctx.set_line_width(9.0) ctx.set_line_cap(cairo.LINE_CAP_ROUND) ctx.set_line_join(cairo.LINE_JOIN_ROUND) ctx.set_source_rgb(*font.color) PangoCairo.show_layout(ctx, lyt) ctx.new_path() ctx.restore() if debug: rectangle(ctx, ink.x, ink.y, ink.width, ink.height, True, 2.0, (0, 1, 0)) rectangle(ctx, obj.x, obj.y, obj.width, obj.height, True, 2.0, (0.8, 0.8, 0))
def prepare(self): fo = cairo.FontOptions() fo.set_antialias(cairo.Antialias.NONE) fo.set_hint_style(cairo.HintStyle.FULL) fo.set_hint_metrics(cairo.HintMetrics.ON) self.matrix.ctx.set_font_options(fo) self.matrix.ctx.select_font_face( "VCR OSD Mono", cairo.FontSlant.NORMAL, cairo.FontWeight.NORMAL ) self.matrix.ctx.set_font_size(21) self._text_extents = self.matrix.ctx.text_extents("99:99")
def draw(self, cr): try: layout = self.layout except AttributeError: layout = cr.create_layout() # set font options # see http://lists.freedesktop.org/archives/cairo/2007-February/009688.html context = layout.get_context() fo = cairo.FontOptions() fo.set_antialias(cairo.ANTIALIAS_DEFAULT) fo.set_hint_style(cairo.HINT_STYLE_NONE) fo.set_hint_metrics(cairo.HINT_METRICS_OFF) pangocairo.context_set_font_options(context, fo) # set font font = pango.FontDescription() font.set_family(self.pen.fontname) font.set_absolute_size(self.pen.fontsize * pango.SCALE) layout.set_font_description(font) # set text layout.set_text(self.t) # cache it self.layout = layout else: cr.update_layout(layout) width, height = layout.get_size() width = float(width) / pango.SCALE height = float(height) / pango.SCALE cr.move_to(self.x - self.w / 2, self.y) if self.j == self.LEFT: x = self.x elif self.j == self.CENTER: x = self.x - 0.5 * width elif self.j == self.RIGHT: x = self.x - width else: assert 0 y = self.y - height cr.move_to(x, y) cr.set_source_rgba(*self.pen.color) cr.show_layout(layout)
def render_barcode_to_cairo_context(self, context, ax, ay, aw, ah, barcode=None): if not barcode: barcode = self.barcode context.save() context.identity_matrix() font_options = cairo.FontOptions() font_options.set_hint_style(cairo.HINT_STYLE_NONE) font_options.set_hint_metrics(cairo.HINT_METRICS_OFF) context.reset_clip() context.set_font_options(font_options) context.rectangle(ax, ay, aw, ah) context.clip() if self.color_margin: self.render_rectangle_to_cairo_context(context, ax, ay, aw, ah, self.color_margin) ax += self.margin_left ay += self.margin_top aw -= (self.margin_right + self.margin_left) ah -= (self.margin_bottom + self.margin_top) context.reset_clip() context.rectangle(ax, ay, aw, ah) context.clip() if self.color_bg: self.render_rectangle_to_cairo_context(context, ax, ay, aw, ah, self.color_bg) for index, (bx, by, bw, bh, value) in enumerate(barcode.get_bar_geometries()): if self.text_top: by = 1.0 - bh rx, ry, rw, rh = ax + bx * aw, ay + by * ah, bw * aw, bh * ah if value and self.color_on: self.render_rectangle_to_cairo_context(context, rx, ry, rw, rh, self.color_on) elif not value and self.color_off: self.render_rectangle_to_cairo_context(context, rx, ry, rw, rh, self.color_off) for index, (bx, by, bw, bh, text) in enumerate(barcode.get_unicode_geometries()): if self.text_top: by = 0.0 rx, ry, rw, rh = ax + bx * aw, ay + by * ah, bw * aw, bh * ah self.render_text_to_cairo_context(context, rx, ry, rw, rh, text, self.color_text) context.restore()
def paint_txt(ctx, txt, box): font_option = cairo.FontOptions() font_option.set_antialias(cairo.Antialias.SUBPIXEL) ctx.set_source_rgb(0, 0, 0) ctx.set_font_options(font_option) ctx.select_font_face("Purisa", cairo.FONT_SLANT_ITALIC, cairo.FONT_WEIGHT_BOLD) ctx.set_font_size(60) # ctx.set_operator(cairo.OPERATOR_ADD) x = box[0]; y = box[1] + 50 w = box[2] - box[0] + 1 h = box[3] - box[1] + 1 ctx.move_to(x, y) ctx.show_text(txt)
def draw_png(filename): surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 512, 256) c = cairo.Context(surface) c.select_font_face("Courier New") c.set_font_size(28) fo = cairo.FontOptions() fo.set_antialias(cairo.ANTIALIAS_DEFAULT) c.set_font_options(fo) c.move_to(50, 50) c.show_text("Antialias Default") fo = cairo.FontOptions() fo.set_antialias(cairo.ANTIALIAS_NONE) c.set_font_options(fo) c.move_to(50, 100) c.show_text("Antialias None") # c.set_antialias(cairo.ANTIALIAS_DEFAULT) c.arc(170, 170, 50, 0, 2 * math.pi) c.set_source_rgba(1, 0, 0, 1) c.fill() c.set_antialias(cairo.ANTIALIAS_NONE) c.arc(370, 170, 50, 0, 2 * math.pi) c.set_source_rgba(1, 0, 0, 1) c.fill() surface.write_to_png(filename)
def cairo_text_bbox(text, font_params, spacing=0, scale=1.0): surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 8, 8) ctx = cairo.Context(surf) # The scaling must match the final context. # If not there can be a mismatch between the computed extents here # and those generated for the final render. ctx.scale(scale, scale) font = cairo_font(font_params) if use_pygobject: status, attrs, plain_text, _ = pango.parse_markup(text, len(text), '\0') layout = pangocairo.create_layout(ctx) pctx = layout.get_context() fo = cairo.FontOptions() fo.set_antialias(cairo.ANTIALIAS_SUBPIXEL) pangocairo.context_set_font_options(pctx, fo) layout.set_font_description(font) layout.set_spacing(spacing * pango.SCALE) layout.set_text(plain_text, len(plain_text)) layout.set_attributes(attrs) li = layout.get_iter() # Get first line of text baseline = li.get_baseline() / pango.SCALE re = layout.get_pixel_extents()[1] # Get logical extents extents = (re.x, re.y, re.x + re.width, re.y + re.height) else: # pyGtk attrs, plain_text, _ = pango.parse_markup(text) pctx = pangocairo.CairoContext(ctx) pctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL) layout = pctx.create_layout() layout.set_font_description(font) layout.set_spacing(spacing * pango.SCALE) layout.set_text(plain_text) layout.set_attributes(attrs) li = layout.get_iter() # Get first line of text baseline = li.get_baseline() / pango.SCALE #print('@@ EXTENTS:', layout.get_pixel_extents()[1], spacing) extents = layout.get_pixel_extents()[1] # Get logical extents return [extents[0], extents[1], extents[2], extents[3], baseline]
def __init__(self, filelist): gobject.GObject.__init__(self) self._filelist = filelist self._filedict = {} self._pagemap = {} self._bookheight = 0 self._count = 0 self._pagecount = 0 self._screen = gtk.gdk.screen_get_default() self._old_fontoptions = self._screen.get_font_options() options = cairo.FontOptions() options.set_hint_style(cairo.HINT_STYLE_MEDIUM) options.set_antialias(cairo.ANTIALIAS_GRAY) options.set_subpixel_order(cairo.SUBPIXEL_ORDER_DEFAULT) options.set_hint_metrics(cairo.HINT_METRICS_DEFAULT) self._screen.set_font_options(options) self._temp_win = gtk.Window() self._temp_view = widgets._WebView() settings = self._temp_view.get_settings() settings.props.default_font_family = 'DejaVu LGC Serif' settings.props.sans_serif_font_family = 'DejaVu LGC Sans' settings.props.serif_font_family = 'DejaVu LGC Serif' settings.props.monospace_font_family = 'DejaVu LGC Sans Mono' settings.props.enforce_96_dpi = True #FIXME: This does not seem to work #settings.props.auto_shrink_images = False settings.props.enable_plugins = False settings.props.default_font_size = 12 settings.props.default_monospace_font_size = 10 settings.props.default_encoding = 'utf-8' sw = gtk.ScrolledWindow() sw.set_policy(gtk.POLICY_NEVER, gtk.POLICY_NEVER) self._dpi = 96 sw.set_size_request(_mm_to_pixel(PAGE_WIDTH, self._dpi), _mm_to_pixel(PAGE_HEIGHT, self._dpi)) sw.add(self._temp_view) self._temp_win.add(sw) self._temp_view.connect('load-finished', self._page_load_finished_cb) self._temp_win.show_all() self._temp_win.unmap() self._temp_view.open(self._filelist[self._count])
def create_layout (self, text, markup=True): cr = self.cr layout = cr.create_layout () font_options = cairo.FontOptions () font_options.set_hint_metrics (cairo.HINT_METRICS_OFF) pangocairo.context_set_font_options (layout.get_context (), font_options) if markup: layout.set_markup (text) else: layout.set_text (text) return layout
def get_cairo_font_options(self, key="font-hinting", default="normal"): """Returns a FontOptions with the right hinting set""" import cairo options = cairo.FontOptions() hinting = self.get(key, default).lower() options.set_hint_style({ "none": cairo.HINT_STYLE_NONE, "slight": cairo.HINT_STYLE_SLIGHT, "light": cairo.HINT_STYLE_SLIGHT, "medium": cairo.HINT_STYLE_MEDIUM, "full": cairo.HINT_STYLE_FULL, "normal": cairo.HINT_STYLE_DEFAULT, "default": cairo.HINT_STYLE_DEFAULT, }[hinting]) return options
def __init__(self, context, width, height): fo = cairo.FontOptions() fo.set_antialias(cairo.ANTIALIAS_NONE) context.set_font_options(fo) context.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) context.set_font_size(10) self.context = context self.width = width self.height = height self.text = [] self._lines = 5 self._line_height = self.height / self._lines self._sliding = False self._slide_frame = 0
def Render(self, pos, size): self.ClearTexture(self.pixelbuffer) self.EnableBlending(True) self.BlendingFunction(OBS.GS_BLEND_ONE, OBS.GS_BLEND_INVSRCALPHA, 1.0) surface = cairo.ImageSurface.create_for_data(self.pixelbuffer, cairo.FORMAT_ARGB32, self.width, self.height) ctx = cairo.Context(surface) ctx.set_source_rgb(0, 1, 0) #ctx.select_font_face("Digital-7 Mono", cairo.FONT_SLANT_NORMAL,cairo.FONT_WEIGHT_NORMAL) font = cairo.FontOptions() current_time = datetime.now() stringtime = current_time.strftime( '%d %b %H:%M:%S:%f')[:-3] + " UTC" + datetime.now( timezone.utc).astimezone().strftime('%z') print("size.x " + str(size.x)) print("size.x " + str(size.y)) #fit text to box for x in reversed(range(self.height)): #font size ctx.set_font_size(x) #rendered size (tx, ty, width, height, dx, dy) = ctx.text_extents(stringtime) if (height < self.height and width < self.width): ctx.set_font_size(x) break (x, y, width, height, dx, dy) = ctx.text_extents(stringtime) #position text ctx.move_to(self.width / 2 - width / 2, self.height / 2 + height / 2) #draw ctx.show_text(stringtime) surface.finish() self.DrawSprite(0xffffffff, pos.x, pos.y) self.BlendingFunction(OBS.GS_BLEND_SRCALPHA, OBS.GS_BLEND_INVSRCALPHA, 1.0)
def np_text(text, fontname='sans', fontsize=48, angle=0): ''' Generate an text within an array :Parameters: `text` : str Text to be generated `fontname` : str Font family name `fontsize` : int Font size `angle` : float Text angle ''' # Dummy surface to get text extents surface = cairo.ImageSurface(cairo.FORMAT_A8, 1, 1) ctx = cairo.Context(surface) ctx.select_font_face(fontname) ctx.set_font_size(fontsize) (x, y, w, h, dx, dy) = ctx.text_extents(text) size = (int(np.sqrt(w**2+h**2)+1)//4)*4+4 # Actual surface surface = cairo.ImageSurface(cairo.FORMAT_A8, size, size) ctx = cairo.Context(surface) options = cairo.FontOptions() options.set_antialias(cairo.ANTIALIAS_SUBPIXEL) options.set_hint_style(cairo.HINT_STYLE_FULL) ctx.set_font_options(options) ctx.set_source_rgba(0,0,0,0) ctx.paint() ctx.set_source_rgba(1,1,1,1) ctx.select_font_face(fontname) ctx.set_font_size(fontsize) ctx.move_to(size//2,size//2) ctx.rotate(angle) ctx.rel_move_to(-w//2,h//2) ctx.show_text(text) # Make an array oput of surface buf = surface.get_data() Z = np.frombuffer(buf, np.uint8) Z.shape = (size,size,1) return np_crop(Z,0)
def get_size(text, font_name, font_size): width, height = 1, 1 surface = cairo.ImageSurface(cairo.FORMAT_RGB24, width, height) cr = cairo.Context(surface) cr.scale(1, 1) fo = cairo.FontOptions() fo.set_antialias(cairo.ANTIALIAS_NONE) utf8 = text cr.select_font_face(font_name, cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) cr.set_font_options(fo) cr.set_font_size(font_size) #print(cr.text_extents(utf8)) return cr.text_extents(utf8)[2:4]
def _prepare_line_context(self, line_surf, x, y, width, height): line_context = cairo.Context(line_surf) f_o = cairo.FontOptions() f_o.set_antialias(cairo.ANTIALIAS_SUBPIXEL) f_o.set_hint_style(cairo.HINT_STYLE_SLIGHT) f_o.set_hint_metrics(cairo.HINT_METRICS_ON) line_context.set_font_options(f_o) r, g, b, a = self._get_color(self.session.cfg.default_background_color) line_context.set_source_rgba(r, g, b, a) line_context.rectangle(0, 0, width, height) line_context.fill() line_p_context = pangocairo.CairoContext(line_context) if sys.platform.startswith('win'): line_p_context.set_antialias(cairo.ANTIALIAS_DEFAULT) else: line_p_context.set_antialias(cairo.ANTIALIAS_SUBPIXEL) return (line_context, line_p_context)
def _cast_inline(self, LINE, runinfo, F, FSTYLE): C = cast_mono_line(LINE, self.char, runinfo, F + self['mathvariant']) C['x'] = 0 C['y'] = FSTYLE['shift'] self._cad = C['advance'] ink = cairo.ScaledFont( C['fstyle']['font'], cairo.Matrix(yy=C['fstyle']['fontsize'], xx=C['fstyle']['fontsize']), cairo.Matrix(), cairo.FontOptions()) self._rise = -ink.text_extents(self.char[-1])[1] self._icorrection = self._rise * self[ 'correct'] * 0.17632698070846498 # tan(10°) charwidth = self._cad + self._icorrection return [ C ], charwidth, C['ascent'], C['descent'], None, (self._draw_annot, 0, 0)