Search code examples
cgtk3cairo

How to show linear gradient with color rgb(248, 205, 205, 1) on gtk3 drawing area?


I am trying to draw pattern linear gradient with color rgba(248, 205, 205, 1). I've seen a linear gradient in GtkColorChooserWidget with color rgb(248, 205, 205). But when i tried to draw it with Cairo in Gtk3 drawing area, it is not showing (black color showing). How to show linear gradient with color rgb(248, 205, 205, 1)?

Photo from GtkColorChooserWidget :rgb(248, 205, 205) on gtkcolorchooser

#include <cairo.h>
#include <gtk/gtk.h>

void draw_gradient2(cairo_t *);
static gboolean on_draw_event(GtkWidget *widget, cairo_t *cr, gpointer user_data){         
  draw_gradient2(cr);
  return FALSE;
}

void draw_gradient2(cairo_t *cr){
    int width = 400;
    int height = 50;

    cairo_pattern_t *gradient;
    gradient =cairo_pattern_create_linear(0.0, 0.0,  width, 0.0);
    cairo_pattern_add_color_stop_rgba (gradient, 0.0, 248/256, 205/256, 205/256, 0.3);
    cairo_pattern_add_color_stop_rgba (gradient, 1.0, 248/256, 205/256, 205/256, 1);

    cairo_set_source (cr, gradient);
    cairo_paint (cr);
    cairo_pattern_destroy (gradient);
}

int main(int argc, char *argv[]){
  GtkWidget *window;
  GtkWidget *darea;  

  gtk_init(&argc, &argv);

  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

  darea = gtk_drawing_area_new();
  gtk_container_add(GTK_CONTAINER (window), darea);

  g_signal_connect(G_OBJECT(darea), "draw", G_CALLBACK(on_draw_event), NULL);  
  g_signal_connect(G_OBJECT(window), "destroy",G_CALLBACK(gtk_main_quit), NULL);

  gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
  gtk_window_set_default_size(GTK_WINDOW(window), 400, 50); 
  gtk_window_set_title(GTK_WINDOW(window), "Linear gradients");

  gtk_widget_set_app_paintable(window, TRUE);
  gtk_widget_show_all(window);

  gtk_main();
  return 0;
}

Solution

  • In your code:

    cairo_pattern_add_color_stop_rgba (gradient, 0.0, 248/256, 205/256, 205/256, 0.3)
    

    You are doing integer division when calling a function that expects doubles in the range [0.0, 1.0]. So the result of 248/256 is 0 as it is integer division. Only than 0 is promoted to double as it is passed to your function.

    So If you change the divisions from to 248.0 / 256.0 the function will get the result of a floating point division.