Python pyCairo:如何调整图像的大小和位置?

Python pyCairo:如何调整图像的大小和位置?,python,cairo,pycairo,Python,Cairo,Pycairo,基于这个问题,我尝试创建代码,重新缩放图像并将其放置在特定位置,如下面的代码所示(例如,在本例中,图像应显示在基础矩形的“上方”)。但是,我似乎无法使图像显示在正确的位置 我希望知道我必须改变什么,以便正确缩放和定位图像 import cairo if not cairo.HAS_PDF_SURFACE: raise SystemExit('cairo was not compiled with PDF support') def draw_image(ctx, image, top

基于这个问题,我尝试创建代码,重新缩放图像并将其放置在特定位置,如下面的代码所示(例如,在本例中,图像应显示在基础矩形的“上方”)。但是,我似乎无法使图像显示在正确的位置

我希望知道我必须改变什么,以便正确缩放和定位图像

import cairo
if not cairo.HAS_PDF_SURFACE:
    raise SystemExit('cairo was not compiled with PDF support')


def draw_image(ctx, image, top, left, height, width):
    """Draw a scaled image on a given context."""
    image_surface = cairo.ImageSurface.create_from_png(image)
    # calculate proportional scaling
    img_height = image_surface.get_height()
    img_width = image_surface.get_width()
    width_ratio = float(width) / float(img_width)
    height_ratio = float(height) / float(img_height)
    scale_xy = min(height_ratio, width_ratio)
    # scale image and add it
    ctx.save()
    ctx.scale(scale_xy, scale_xy)
    ctx.translate(left, top)
    ctx.set_source_surface(image_surface)

    ctx.paint()
    ctx.restore()


def draw_box(ctx, left, top, width, height):
    """Draw a box on a given context."""
    ctx.rectangle(left, top, width, height)
    ctx.set_source_rgb(1, 1, 1)
    ctx.fill()
    ctx.rectangle(left, top, width, height)
    ctx.set_source_rgb(0, 0, 0)
    ctx.stroke()


# A4 Page (in points)
surface = cairo.PDFSurface("box.pdf", 595, 842)
context = cairo.Context(surface)
# sizes (in points)
height = 250
width = 180
margin = 20
# draw boxes
draw_box(context, margin, margin, width, height)
draw_box(context, margin + width, margin + height, width, height)
# draw images - SHOULD be superimposed over rectangles, but are NOT
image = "hello.png"
draw_image(context, image, margin, margin, height, width)
draw_image(context, image, margin + height, margin + width, height, width)

切换缩放和平移的顺序。先翻译,然后缩放。

您不太可能得到好的答案,因为人们不能仅仅运行此代码来测试它。如果可能的话,请用一个自包含的示例更新它(并链接到运行它所需的任何模块/图像/等等),等等。你安装了PyCairo??不可能。@agf-实际上这是一个独立的脚本。。。您在尝试运行它时遇到了哪些问题?唯一需要的模块是cairo。