Guide to implementing a radial gradient using CSS on a cairo surface in gtk4

I am attempting to create a circular shape on a Gtk4 GtkDrawingarea using CSS. The goal is to then save the circle as a PNG file upon clicking on it. However, I am encountering difficulties in transferring the drawing (gradient) from the drawing area to a cairo surface (cairo_surface_t). Is there a way to save the drawing created through CSS? Below is the code snippet:

#include <gtk/gtk.h>

//draw function
static void
draw_function (GtkDrawingArea *darea,
               cairo_t        *cr,
               int             width,
               int             height,
               gpointer        user_data)
{
  GdkDisplay *display = gdk_display_get_default ();
  GtkCssProvider* provider = gtk_css_provider_new ();
  gtk_css_provider_load_from_data (provider, 
                                  "#darea { border-radius: 50%;"
                                  "  background: radial-gradient(#FFFFFF, #000000); "
                                  "}",-1);
  gtk_style_context_add_provider (gtk_widget_get_style_context (GTK_WIDGET (darea)),
                              GTK_STYLE_PROVIDER (provider),GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);

g_object_unref(provider);
}

/*save as png on click*/
void click_event (GtkEventController *gesture,
                           gdouble x,
                           gdouble y,
                           gpointer user_data)
{
 //user_data = darea (widget)
  int w1 = gtk_widget_get_allocated_width(user_data);
  int h1 = gtk_widget_get_allocated_height(user_data);

  /*paintable from the darea widget*/
  GdkPaintable* paintable = gtk_widget_paintable_new (user_data);

 /*take snapshot*/
  GdkSnapshot* snapshot = gtk_snapshot_new();
  gdk_paintable_snapshot (paintable, snapshot, w1, h1); 

  graphene_rect_t *rec = graphene_rect_alloc ();
  GskRenderNode* ren = gsk_cairo_node_new (rec);

  cairo_t* cr = gtk_snapshot_append_cairo (snapshot, rec);
  cairo_surface_t* srf = gsk_cairo_node_get_surface ((GskRenderNode *)ren);

  cairo_surface_write_to_png (srf, "blur.png"); //use it -error Segmentation fault
}


static void
activate (GtkApplication* app,
          gpointer        user_data)
{
  GtkWidget *window;
  window = gtk_application_window_new (app);
  gtk_window_set_title (GTK_WINDOW (window), "Window");
  gtk_window_set_default_size (GTK_WINDOW (window), 200, 200);
  gtk_window_present (GTK_WINDOW (window));


  GtkWidget *darea = gtk_drawing_area_new();
  gtk_widget_set_name (darea, "darea");
  gtk_drawing_area_set_content_width (GTK_DRAWING_AREA (darea), 350);
  gtk_drawing_area_set_content_height (GTK_DRAWING_AREA (darea), 350);
  gtk_drawing_area_set_draw_func (GTK_DRAWING_AREA (darea),
                                  draw_function,
                                  NULL, NULL);
  gtk_window_set_child (GTK_WINDOW (window), darea);

  //create gesture for mouse click event
    GtkGesture * = gtk_gesture_click_new();
    gtk_gesture_single_set_button(GTK_GESTURE_SINGLE(gesture), 0);
    gtk_widget_add_controller(darea,(GTK_EVENT_CONTROLLER(gesture)));
    g_signal_connect (gesture, "pressed", G_CALLBACK (click_event), darea); 

  gtk_window_present (GTK_WINDOW(window));
}

int
main (int    argc,
      char **argv)
{
  GtkApplication *app;
  int status;
  app = gtk_application_new ("org.gtk.example", G_APPLICATION_DEFAULT_FLAGS);
  g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
  status = g_application_run (G_APPLICATION (app), argc, argv);
  g_object_unref (app);

  return status;
}

Unfortunately, the code is not functioning properly and results in a crash!

Answer №1

There appears to be a core issue of comprehension in this scenario. According to the documentation, "GtkDrawingArea is a widget that allows drawing with cairo.....It’s essentially a blank widget; you can draw on it." However, despite this description, no actual drawing takes place in the example provided. Instead, the widget is solely styled using CSS, resulting in an absence of any visual output and consequently causing the program to crash.

Regrettably, GTK4 does not offer a direct method for extracting the pixel data from a widget and converting it into an image file. Users are advised to utilize system tools for such tasks instead. :-(

The documentation explicitly states:

"Stop using gdk_pixbuf_get_from_window() and gdk_cairo_set_source_window() These functions are not supported in GTK 4. Instead, either use backend-specific APIs, or render your widgets using Gtk.WidgetClass.snapshot once you transition to GTK 4."

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Add CSS styling to an ASP.Net webpage that utilizes the default master page

I have developed a new ASP.Net Web Application and inserted the following div in the Default.aspx file: <div id="TestDiv"> Hi, This is CSS test. </div> To style the above div, I included the following CSS in the Site.css file: #TestDiv{ colo ...

Enhance user experience with JQUERY - MouseEnter, Focus, Hover, and Blur

Here is the current code snippet for showing and hiding a footer banner. Everything seems to be working fine except for an issue with MouseOver functionality. The MouseOver feature works as expected, but when a user clicks within the area, the highlight d ...

IE compatibility problem with the alignment of input group buttons and textboxes in Bootstrap v4

Encountering an issue with input group in IE while using bootstrap v4, working fine in Chrome. Specifically using IE 11 Here is my plunkr: input group bootstrap v4 Chrome display: https://i.sstatic.net/yXtEW.png IE display: https://i.sstatic.net/WiRz ...

What is the best way to showcase the contents of an array of objects from JavaScript on an HTML page in a dynamic

Looking for guidance in Javascript as a beginner. For an assignment, I need to create two separate JS files and use them to display data dynamically on an HTML page. One JS file, named data.js, contains an array of objects representing a product catalog. T ...

convert a list of options into a dropdown selection menu

Is there a way to turn a regular menu into a dropdown menu for small devices without modifying the HTML code? I have a responsive design, but I'm not sure how to add that 'hamburger menu' style. Note: I am unable to make changes to the HTML ...

Bringing in linker addresses for C programs

Looking to utilize the address labeled _end from the linker.ld file within main.c. The known value for this address is at least 0x80000000. However, when attempting to import it using extern char _end; in main.c and printing it out, the output only shows 1 ...

Is there a way to locate the source or URL linked to a button on a form or webpage?

Currently, I am extracting data feeds from a webpage by clicking a button that is similar to the 'Login' button displayed on the following link: However, this button acts as a 'Download' request that initiates the download of a csv rep ...

Library for converting HTML to PowerPoint presentations using the .Net framework

I have developed a web-based reporting engine that generates reports in HTML/CSS format. For exporting to PDF, I am using Essential Objects' HTMLtoPDF library and for exporting to Excel, EPPlus. Despite this, I am facing difficulty finding a .NET libr ...

Tips for creating animated navigation buttons that guide users to specific sections within interior pages

Recently, a client approached me with an interesting challenge: They want a homepage design that features the navigation loading in a specific location. However, once a user clicks on one of the nav buttons, they would like the entire navigation to anima ...

Alignment of Images in a Navbar According to Height

I am in the process of developing a website using Bootstrap 4 and I am trying to create a centered navbar with the navbar-brand. By placing navbar-nav on each side of the navbar-brand, I was able to achieve this layout. However, my issue is that the navb ...

Are background styles complete without incorporating quotations?

Let's say I want to include a background image, my code might look like this: background: url(/images/button_bg.png) repeat-x scroll left bottom #146BAE However, when I check the code in Firebug, it shows: background: url("/images/button_bg.png") r ...

Pressing a button will reset the input spinner in Bootstrap

Is there a way to reset the bootstrap input spinner by clicking a button? I attempted using document.getelementbyId().value = "0" and also tried using reset(), but neither method worked. Any suggestions on how to successfully reset it? function resetScor ...

Simply by loading Bootstrap, it is causing the animation parameters to become disrupted

Currently, I am experimenting with implementing a frontend code I discovered online for simulating a dice roll. If you are interested, you can find the code in this repository: https://codesandbox.io/s/xjk3xqnprw?file=/styles.css:0-4535 Here is the HTML ...

What is the reason behind using <script> tag for scripts, instead of using <style> tag for external CSS files?

A family member who is new to Web Development posed an interesting question to me. Why do we use <script src="min.js"></script> and <link rel="stylesheet" href="min.css">? Why not simply use <style href="min.css"></style>? Wh ...

Unexpectedly, the variable (C) in the code for populating an array has been

As I delve into the world of coding, I encountered an issue that has me puzzled. In my 'for' loop, at the second last input something strange happens - 'control' is suddenly replaced by that input (confirmed with a printf statement). An ...

Sass fails to import the theme for the angular material checkbox

I'm facing an issue where, despite specifying imports in my SCSS file and setting up a custom theme, the checkbox styles are not visible except for those related to typography. This is what my SCSS file looks like: @import "~bootstrap/scss/bootstrap ...

Adjust the height based on the size of another div when the window is resized

Two divs are positioned next to each other with a width of 50% each. One of the divs contains more text, causing it to be longer than the other div. A javascript function adjusts the height of the shorter div to match the height of the longer div, ensuring ...

Adjusting images of various sizes within a single row to fit accordingly

I am faced with a challenge of aligning a set of images on a webpage, each with varying heights, widths, and aspect ratios. My goal is to arrange them in a way that they fit seamlessly across the screen while ensuring their heights are uniform. Adjusting ...

Footer sidebar of Material Dashboard 2 (free edition) from Innovative Schedule

I noticed in the demonstration of Creative Tim's Material Dashboard 2 (free version) that the sidebar footer takes up a significant amount of space, up to 360px tall. This causes some menu items to be hidden if the browser window is not tall enough. ...

Eliminate the flickering effect on the dropdown menu

Is there a way to eliminate the annoying 'flicker' effect on my menu? Whenever I click on 'Dropdown 1', I notice that Test 1 and Test 2 flicker. My assumption is that this is due to my use of the !important declaration. Any suggestion ...