2011-08-22 16 views
8

He intentado crear un código que reescala y coloca una imagen en una posición específica, como se muestra en el siguiente código (en este caso, por ejemplo, las imágenes deben aparecer "sobre" los rectángulos subyacentes). Sin embargo, parece que no puedo hacer que la imagen aparezca en la (s) ubicación (es) correcta (s).pyCairo: ¿Cómo cambiar el tamaño y posicionar una imagen?

Me gustaría saber qué debo cambiar, para poder escalar y posicionar una imagen correctamente.

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) 
+0

Es poco probable que obtenga buenas respuestas porque la gente no puede simplemente ejecutar este código para probarlo. Actualícelo con un ejemplo independiente si es posible (y enlace a los módulos/imágenes/etc. necesarios para ejecutarlo) – agf

+6

Espere. Usted * INSTALADO * PyCairo ?? Imposible. – batman

+0

@agf - En realidad, esta es una secuencia de comandos independiente ... ¿Qué problemas te encontraste al tratar de ejecutarlo? El único módulo necesario es cairo. – Derek

Respuesta

3

Cambie el orden de escala y traslade. Traducir primero, luego escalar.

Cuestiones relacionadas