Search code examples
cgtkcairo

Scale part of pixbuf acording scale factor in cairo


I have a surface created from pixbuf

gint scale = gtk_widget_get_scale_factor (drawing_area);

cairo_surface_t surface = gdk_cairo_surface_create_from_pixbuf (pixbuf, scale, gtk_widget_get_window (drawing_area));

I want to draw a part of this surface in drawing area but scaled if scale changed

#define DIGIT_WIDTH  20
#define DIGIT_HEIGTH 30

/* same code */

int width = gtk_widget_get_allocated_width (drawing_area);

cairo_set_source_surface (cr, surface, width - DIGIT_WIDTH, 5);
cairo_rectangle (cr, width - DIGIT_WIDTH, 5, DIGIT_WIDTH, DIGIT_HEIGTH);
cairo_fill (cr);

How can I apply scale factor to DIGIT_WIDTH and DIGIT_HEIGTH?


Solution

  • If I understood you correctly:

    int width = gtk_widget_get_allocated_width (drawing_area);
    
    cairo_rectangle (cr, width - DIGIT_WIDTH, 5, DIGIT_WIDTH, DIGIT_HEIGTH);
    cairo_scale(cr, scale, scale);
    cairo_set_source_surface (cr, pixbuf, width - DIGIT_WIDTH, 5);
    cairo_fill (cr);
    

    It might be that you need to "unapply" the scaling to the source. I'm not sure right now and too lazy to test:

    cairo_set_source_surface (cr, pixbuf, (width - DIGIT_WIDTH) / (double) scale, 5. / scale);