當前位置: 首頁>>代碼示例>>Python>>正文


Python Context.paint方法代碼示例

本文整理匯總了Python中cairo.Context.paint方法的典型用法代碼示例。如果您正苦於以下問題:Python Context.paint方法的具體用法?Python Context.paint怎麽用?Python Context.paint使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在cairo.Context的用法示例。


在下文中一共展示了Context.paint方法的5個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: MapSurface

# 需要導入模塊: from cairo import Context [as 別名]
# 或者: from cairo.Context import paint [as 別名]
class MapSurface(object):
    """wrapper to render the map to svg/png"""

    def __init__(self, hexmap=None, filename=None, width=None, height=None, size=None):
        self.hexmap = hexmap
        if self.hexmap is None:
            raise ValueError("No map was passed to {}".format(self.__class__.__name__))
        self.surface_name = filename or "test.svg"
        self.size = size or 32.0
        self.surface_width = width
        if self.surface_width is None:
            self.surface_width = (self.hexmap.map.cols + .5) * self.size * SQRT3
        self.surface_height = height
        if self.surface_height is None:
            self.surface_height = (self.hexmap.map.rows * 1.5 + .25) * self.size
        self.layer = []

        # build base map
        self.surface = SVGSurface(self.surface_name + ".svg", self.surface_width, self.surface_height)
        self.context = Context(self.surface)
        # background: magenta
        self.context.save()
        self.context.set_source_rgb(1.0, 0.0, 1.0)
        self.context.paint()
        self.context.restore()

    def add_layer(self, renderer_cls, position=None):
        if not position:
            self.layer.append(renderer_cls(self))
        else:
            self.layer.insert(position, renderer_cls(self))

    def render(self):
        print "Rendering {} ({}x{})".format(self.surface_name, self.surface_width, self.surface_height)
        for renderer in self.layer:
            renderer.render()

    def finalise(self, with_png=False):
        print "finalising:"
        if with_png is True:
            print "PNG"
            self.surface.write_to_png(self.surface_name + ".png")
        print "SVG"
        self.surface.finish()
        print "DONE!"
開發者ID:,項目名稱:,代碼行數:47,代碼來源:

示例2: make_label

# 需要導入模塊: from cairo import Context [as 別名]
# 或者: from cairo.Context import paint [as 別名]
def make_label(text, filename, size=12, angle=0):
    '''
    Parameters:
    -----------
    text : string
        Text to be displayed
    filename : string
        Path to a font
    size : int
        Font size in 1/64th points
    angle : float
        Text angle in degrees
    '''
    face = Face(filename)
    face.set_char_size( size*64 )
    # FT_Angle is a 16.16 fixed-point value expressed in degrees.
    angle = FT_Angle(angle * 65536)
    matrix  = FT_Matrix( FT_Cos( angle ),
                         - FT_Sin( angle ),
                         FT_Sin( angle ) ,
                         FT_Cos( angle ) )
    flags = FT_LOAD_RENDER
    pen = FT_Vector(0,0)
    FT_Set_Transform( face._FT_Face, byref(matrix), byref(pen) )
    previous = 0
    xmin, xmax = 0, 0
    ymin, ymax = 0, 0
    for c in text:
        face.load_char(c, flags)
        kerning = face.get_kerning(previous, c)
        previous = c
        bitmap = face.glyph.bitmap
        pitch  = face.glyph.bitmap.pitch
        width  = face.glyph.bitmap.width
        rows   = face.glyph.bitmap.rows
        top    = face.glyph.bitmap_top
        left   = face.glyph.bitmap_left
        pen.x += kerning.x
        x0 = (pen.x >> 6) + left
        x1 = x0 + width
        y0 = (pen.y >> 6) - (rows - top)
        y1 = y0 + rows
        xmin, xmax = min(xmin, x0),  max(xmax, x1)
        ymin, ymax = min(ymin, y0), max(ymax, y1)
        pen.x += face.glyph.advance.x
        pen.y += face.glyph.advance.y

    L = ImageSurface(FORMAT_A8, xmax-xmin, ymax-ymin)
    previous = 0
    pen.x, pen.y = 0, 0
    ctx = Context(L)
    for c in text:
        face.load_char(c, flags)
        kerning = face.get_kerning(previous, c)
        previous = c
        bitmap = face.glyph.bitmap
        pitch  = face.glyph.bitmap.pitch
        width  = face.glyph.bitmap.width
        rows   = face.glyph.bitmap.rows
        top    = face.glyph.bitmap_top
        left   = face.glyph.bitmap_left
        pen.x += kerning.x
        x = (pen.x >> 6) - xmin + left
        y = - (pen.y >> 6) + ymax - top
        if (width > 0):
            glyph_surface = make_image_surface(face.glyph.bitmap)
            ctx.set_source_surface(glyph_surface, x, y)
            ctx.paint()
        pen.x += face.glyph.advance.x
        pen.y += face.glyph.advance.y

    L.flush()
    return L
開發者ID:moyogo,項目名稱:freetype-py,代碼行數:75,代碼來源:wordle-cairo.py

示例3: RuntimeError

# 需要導入模塊: from cairo import Context [as 別名]
# 或者: from cairo.Context import paint [as 別名]
    raise RuntimeError('pitch != width * 4 for color bitmap: Please report this.')
bitmap = np.array(bitmap.buffer, dtype=np.uint8).reshape((bitmap.rows,bitmap.width,4))

I = ImageSurface(FORMAT_ARGB32, width, rows)
try:
    ndI = np.ndarray(shape=(rows,width), buffer=I.get_data(),
                     dtype=np.uint32, order='C',
                     strides=[I.get_stride(), 4])
except NotImplementedError:
    raise SystemExit("For python 3.x, you need pycairo >= 1.11+ (from https://github.com/pygobject/pycairo)")

# Although both are 32-bit, cairo is host-order while
# freetype is small endian.
ndI[:,:] = bitmap[:,:,3] * 2**24 + bitmap[:,:,2] * 2**16 + bitmap[:,:,1] * 2**8 + bitmap[:,:,0]
I.mark_dirty()

surface = ImageSurface(FORMAT_ARGB32, 2*width, rows)
ctx = Context(surface)

ctx.set_source_surface(I, 0, 0)
ctx.paint()

ctx.set_source_surface(I, width/2, 0)
ctx.paint()

ctx.set_source_surface(I, width , 0)
ctx.paint()

surface.write_to_png("emoji-color-cairo.png")
Image.open("emoji-color-cairo.png").show()
開發者ID:moyogo,項目名稱:freetype-py,代碼行數:32,代碼來源:emoji-color-cairo.py

示例4: generateOverlay

# 需要導入模塊: from cairo import Context [as 別名]
# 或者: from cairo.Context import paint [as 別名]
def generateOverlay(text,
                    font,
                    showFlumotion,
                    showCC,
                    showXiph,
                    width, height):
    """Generate an transparent image with text + logotypes rendered on top
    of it suitable for mixing into a video stream
    @param text: text to put in the top left corner
    @type text: str
    @param font: font description used to render the text
    @type: str
    @param showFlumotion: if we should show the flumotion logo
    @type showFlumotion: bool
    @param showCC: if we should show the Creative Common logo
    @type showCC: bool
    @param showXiph: if we should show the xiph logo
    @type showXiph: bool
    @param width: width of the image to generate
    @type width: int
    @param height: height of the image to generate
    @type height: int
    @returns: raw image and if images or if text overflowed
    @rtype: 3 sized tuple of string and 2 booleans
    """
    from cairo import ImageSurface
    from cairo import Context

    image = ImageSurface(cairo.FORMAT_ARGB32, width, height)
    context = Context(image)

    subImages = []
    if showXiph:
        subImages.append(os.path.join(configure.imagedir, '36x36', 'xiph.png'))
    if showCC:
        subImages.append(os.path.join(configure.imagedir, '36x36', 'cc.png'))
    if showFlumotion:
        subImages.append(os.path.join(configure.imagedir, '36x36',
                                      'fluendo.png'))

    imagesOverflowed = False

    offsetX = BORDER
    for subPath in subImages:
        sub = ImageSurface.create_from_png(subPath)
        subX = sub.get_width()
        subY = sub.get_height()
        offsetY = height - subY - BORDER
        context.set_source_surface(sub, offsetX, offsetY)
        context.paint()
        if (offsetX + subX) > width:
            imagesOverflowed = True
        offsetX += subX + BORDER

    textOverflowed = False
    if text:
        pcContext = pangocairo.CairoContext(context)
        pangoLayout = pcContext.create_layout()
        if font is not None:
            font = pango.FontDescription(font)
            if not font.get_family() or \
               not font.get_family().lower() in [family.get_name().lower()
                    for family in pangoLayout.get_context().list_families()]:
                font.set_family(FONT)
            if font.get_size() == 0:
                font.set_size(FONT_SIZE)
        else:
            font = pango.FontDescription('%s %s' % (FONT, FONT_PROPS))
        pangoLayout.set_font_description(font)

        context.move_to(TEXT_XOFFSET+2, TEXT_YOFFSET+2)
        pangoLayout.set_markup('<span foreground="black" >%s</span>' % text)
        pcContext.show_layout(pangoLayout)
        context.move_to(TEXT_XOFFSET, TEXT_YOFFSET)
        pangoLayout.set_markup('<span foreground="white" >%s</span>' % text)
        pcContext.show_layout(pangoLayout)

        textWidth, textHeight = pangoLayout.get_pixel_size()
        if textWidth > width:
            textOverflowed = True

    if cairo.version < '1.2.6':
        buf = image.get_data_as_rgba()
    else:
        buf = image.get_data()

    return buf, imagesOverflowed, textOverflowed
開發者ID:offlinehacker,項目名稱:flumotion,代碼行數:89,代碼來源:genimg.py

示例5: do_draw

# 需要導入模塊: from cairo import Context [as 別名]
# 或者: from cairo.Context import paint [as 別名]
    def do_draw(self, context: cairo.Context) -> bool:
        if not self.adjustment or self.adjustment.get_upper() <= 0:
            return False

        height = self.get_allocated_height()
        width = self.get_allocated_width()

        if width <= 0 or height <= 0:
            return False

        base_bg, base_outline, handle_overdraw, handle_outline = (
            self.get_map_base_colors())

        x0 = self.overdraw_padding + 0.5
        x1 = width - 2 * x0
        height_scale = height * self.get_height_scale()

        if self._cached_map is None:
            surface = cairo.Surface.create_similar(
                context.get_target(), cairo.CONTENT_COLOR_ALPHA, width, height)
            cache_ctx = cairo.Context(surface)
            cache_ctx.set_line_width(1)

            cache_ctx.rectangle(x0, -0.5, x1, height_scale + 0.5)
            cache_ctx.set_source_rgba(*base_bg)
            cache_ctx.fill()

            # We get drawing coordinates by tag to minimise our source
            # colour setting, and make this loop slightly cleaner.
            tagged_diffs = self.chunk_coords_by_tag()

            for tag, diffs in tagged_diffs.items():
                cache_ctx.set_source_rgba(*self.fill_colors[tag])
                for y0, y1 in diffs:
                    y0 = round(y0 * height_scale) + 0.5
                    y1 = round(y1 * height_scale) - 0.5
                    cache_ctx.rectangle(x0, y0, x1, y1 - y0)
                cache_ctx.fill_preserve()
                cache_ctx.set_source_rgba(*self.line_colors[tag])
                cache_ctx.stroke()

            cache_ctx.rectangle(x0, -0.5, x1, height_scale + 0.5)
            cache_ctx.set_source_rgba(*base_outline)
            cache_ctx.stroke()

            self._cached_map = surface

        context.set_source_surface(self._cached_map, 0, 0)
        context.paint()

        # Draw our scroll position indicator
        context.set_line_width(1)
        context.set_source_rgba(*handle_overdraw)
        adj_y = self.adjustment.get_value() / self.adjustment.get_upper()
        adj_h = self.adjustment.get_page_size() / self.adjustment.get_upper()
        context.rectangle(
            x0 - self.overdraw_padding, round(height_scale * adj_y) + 0.5,
            x1 + 2 * self.overdraw_padding, round(height_scale * adj_h) - 1,
        )
        context.fill_preserve()
        context.set_source_rgba(*handle_outline)
        context.stroke()

        return True
開發者ID:GNOME,項目名稱:meld,代碼行數:66,代碼來源:chunkmap.py


注:本文中的cairo.Context.paint方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。