Python freetype.Face() Examples

The following are 10 code examples of freetype.Face(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module freetype , or try the search function .
Example #1
Source File: text.py    From RibbaPi with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self,  width, height, frame_queue, repeat, text,
                 steps_per_second=15, pixels_per_step=1, text_size=16,
                 emoji_size=20,
                 text_font="resources/fonts/SFCompactDisplay-Regular.otf",
                 emoji_font="resources/fonts/Apple Color Emoji.ttc"):
        super().__init__(width, height, frame_queue, repeat)

        self.name = "text"
        self.text = text
        self.text_size = text_size
        self.emoji_size = emoji_size
        self.steps_per_second = steps_per_second
        self.pixels_per_step = pixels_per_step

        self.text_face = freetype.Face(text_font)
        self.emoji_face = freetype.Face(emoji_font)

        self.text_face.set_char_size(self.text_size * 64)
        self.emoji_face.set_char_size(self.emoji_size * 64)
        np.set_printoptions(threshold=np.nan, linewidth=300) 
Example #2
Source File: font_to_py.py    From micropython-font-to-py with MIT License 5 votes vote down vote up
def __init__(self, filename, size, minchar, maxchar, monospaced, defchar, charset):
        super().__init__()
        self._face = freetype.Face(filename)
        # .crange is the inclusive range of ordinal values spanning the character set.
        self.crange = range(minchar, maxchar + 1)
        self.monospaced = monospaced
        self.defchar = defchar
        # .charset has all defined characters with '' for those in range but undefined.
        # Sort order is increasing ordinal value of the character whether defined or not,
        # except that item 0 is the default char.
        if defchar is None: # Binary font
            self.charset = [chr(ordv) for ordv in self.crange]
        elif charset == '':
            self.charset = [chr(defchar)] + [chr(ordv) for ordv in self.crange]
        else:
            cl = [ord(x) for x in chr(defchar) + charset if self._face.get_char_index(x) != 0 ]
            self.crange = range(min(cl), max(cl) + 1)  # Inclusive ordinal value range
            cs = [chr(ordv) if chr(ordv) in charset and self._face.get_char_index(chr(ordv)) != 0 else '' for ordv in self.crange]
            # .charset has an item for all chars in range. '' if unsupported.
            # item 0 is the default char. Subsequent chars are in increasing ordinal value.
            self.charset = [chr(defchar)] + cs
        # Populate self with defined chars only
        self.update(dict.fromkeys([c for c in self.charset if c]))
        self.max_width = self.get_dimensions(size)
        self.width = self.max_width if monospaced else 0
        self._assign_values()  # Assign values to existing keys

    # n-pass solution to setting a precise height. 
Example #3
Source File: ftFont.py    From fontgoggles with Apache License 2.0 5 votes vote down vote up
def __init__(self, fontData, *, fontNumber=0, ttFont=None):
        if ttFont is None:
            stream = io.BytesIO(fontData)
            ttFont = TTFont(stream, fontNumber=fontNumber, lazy=True)
        self._ttFont = ttFont
        stream = io.BytesIO(fontData)
        self._ftFace = freetype.Face(stream, index=fontNumber)
        try:
            self._ftFace.set_char_size(self._ftFace.units_per_EM)
        except freetype.FT_Exception as e:
            logging.warning("FreeType error, possibly with unsupported pixel font: %s", e) 
Example #4
Source File: font_to_py.py    From micropython-ili9341 with MIT License 5 votes vote down vote up
def __init__(self, filename, size, minchar, maxchar, monospaced, defchar):
        super().__init__()
        self._face = freetype.Face(filename)
        if defchar is None: # Binary font
            self.charset = [chr(char) for char in range(minchar, maxchar + 1)]
        else:
            self.charset = [chr(defchar)] + [chr(char) for char in range(minchar, maxchar + 1)]
        self.max_width = self.get_dimensions(size)
        self.width = self.max_width if monospaced else 0
        for char in self.charset:  # Populate dictionary
            self._render_char(char)

    # n-pass solution to setting a precise height. 
Example #5
Source File: font.py    From fontdiffenator with Apache License 2.0 5 votes vote down vote up
def __init__(self, path=None, lazy=False, size=1500):
        self.path = path
        self.ttfont = TTFont(self.path)

        has_outlines = self.ttfont.has_key("glyf") or self.ttfont.has_key("CFF ")
        if not has_outlines:
            # Create faux empty glyf table with empty glyphs to make
            # it a valid font, e.g. for old-style CBDT/CBLC fonts
            logger.warning("No outlines present, treating {} as bitmap font".format(self.path))
            self.ttfont["glyf"] = newTable("glyf")
            self.ttfont["glyf"].glyphs = {}
            pen = TTGlyphPen({})
            for name in self.ttfont.getGlyphOrder():
                self.ttfont["glyf"].glyphs[name] = pen.glyph()

        self._src_ttfont = TTFont(self.path)
        self.glyphset = None
        self.recalc_glyphset()
        self.axis_order = None
        self.instance_coordinates = self._get_dflt_instance_coordinates()
        self.instances_coordinates = self._get_instances_coordinates()
        self.glyphs = self.marks = self.mkmks = self.kerns = \
            self.glyph_metrics = self.names = self.attribs = None

        self.ftfont = freetype.Face(self.path)
        self.ftslot = self.ftfont.glyph

        self.size = size
        if self.ftfont.is_scalable:
            self.ftfont.set_char_size(self.size)

        with open(self.path, 'rb') as fontfile:
            self._fontdata = fontfile.read()
        self.hbface = hb.Face.create(self._fontdata)
        self.hbfont = hb.Font.create(self.hbface)

        self.hbfont.scale = (self.size, self.size)

        if not lazy:
            self.recalc_tables() 
Example #6
Source File: font.py    From fontdiffenator with Apache License 2.0 5 votes vote down vote up
def set_variations(self, axes):
        """Instantiate a ttfont VF with axes vals"""
        logger.debug("Setting variations to {}".format(axes))
        if self.is_variable:
            font = instantiateVariableFont(self._src_ttfont, axes, inplace=False)
            self.ttfont = copy(font)
            self.axis_order = [a.axisTag for a in self._src_ttfont['fvar'].axes]
            self.instance_coordinates = {a.axisTag: a.defaultValue for a in
                                    self._src_ttfont['fvar'].axes}
            for axis in axes:
                if axis in self.instance_coordinates:
                    self.instance_coordinates[axis] = axes[axis]
                else:
                    logger.info("font has no axis called {}".format(axis))
            self.recalc_tables()

            coords = []
            for name in self.axis_order:
                coord = FT_Fixed(int(self.instance_coordinates[name]) << 16)
                coords.append(coord)
            ft_coords = (FT_Fixed * len(coords))(*coords)
            FT_Set_Var_Design_Coordinates(self.ftfont._FT_Face, len(ft_coords), ft_coords)
            self.hbface = hb.Face.create(self._fontdata)
            self.hbfont = hb.Font.create(self.hbface)
            self.hbfont.set_variations(self.instance_coordinates)
            self.hbfont.scale = (self.size, self.size)
        else:
            logger.info("Not vf") 
Example #7
Source File: font_tests.py    From nototools with Apache License 2.0 5 votes vote down vote up
def get_rendered_char_height(font_filename, font_size, char, target="mono"):
    if target == "mono":
        render_params = freetype.FT_LOAD_TARGET_MONO
    elif target == "lcd":
        render_params = freetype.FT_LOAD_TARGET_LCD
    render_params |= freetype.FT_LOAD_RENDER

    face = freetype.Face(font_filename)
    face.set_char_size(font_size * 64)
    face.load_char(char, render_params)
    return face.glyph.bitmap.rows 
Example #8
Source File: font.py    From gqn-dataset-renderer with MIT License 5 votes vote down vote up
def __init__(self, font_file, font_pt=40):
        self.font_file = font_file
        self.font_pt = int(font_pt)
        self._face = freetype.Face(font_file)
        self._face.set_pixel_sizes(0, font_pt)
        self._character_map = {}

        for i in range(0, 128):

            # Generate texture
            face = self._face
            face.load_char(chr(i))
            buf = face.glyph.bitmap.buffer
            src = (np.array(buf) / 255.0).astype(np.float32)
            src = src.reshape((face.glyph.bitmap.rows,
                               face.glyph.bitmap.width))
            tex = Texture(
                sampler=Sampler(
                    magFilter=GL_LINEAR,
                    minFilter=GL_LINEAR,
                    wrapS=GL_CLAMP_TO_EDGE,
                    wrapT=GL_CLAMP_TO_EDGE
                ),
                source=src,
                source_channels='R',
            )
            character = Character(
                texture=tex,
                size=np.array([face.glyph.bitmap.width,
                               face.glyph.bitmap.rows]),
                bearing=np.array([face.glyph.bitmap_left,
                                  face.glyph.bitmap_top]),
                advance=face.glyph.advance.x
            )
            self._character_map[chr(i)] = character

        self._vbo = None
        self._vao = None 
Example #9
Source File: fontdemo.py    From rpi_wordclock with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, filename, size):
        self.face = freetype.Face(filename)
        self.face.set_pixel_sizes(0, size) 
Example #10
Source File: font.py    From pyrender with MIT License 5 votes vote down vote up
def __init__(self, font_file, font_pt=40):
        self.font_file = font_file
        self.font_pt = int(font_pt)
        self._face = freetype.Face(font_file)
        self._face.set_pixel_sizes(0, font_pt)
        self._character_map = {}

        for i in range(0, 128):

            # Generate texture
            face = self._face
            face.load_char(chr(i))
            buf = face.glyph.bitmap.buffer
            src = (np.array(buf) / 255.0).astype(np.float32)
            src = src.reshape((face.glyph.bitmap.rows,
                               face.glyph.bitmap.width))
            tex = Texture(
                sampler=Sampler(
                    magFilter=GL_LINEAR,
                    minFilter=GL_LINEAR,
                    wrapS=GL_CLAMP_TO_EDGE,
                    wrapT=GL_CLAMP_TO_EDGE
                ),
                source=src,
                source_channels='R',
            )
            character = Character(
                texture=tex,
                size=np.array([face.glyph.bitmap.width,
                               face.glyph.bitmap.rows]),
                bearing=np.array([face.glyph.bitmap_left,
                                  face.glyph.bitmap_top]),
                advance=face.glyph.advance.x
            )
            self._character_map[chr(i)] = character

        self._vbo = None
        self._vao = None