我有一个用随机函数生成的正弦波。结果点被放入一个数组中,其中索引为 0 到 799(对应于我的 x 值),并且所述索引的值对应于 y 的位置。
现在,我正在尝试创建一个渐变,从 100% alpha 的绿色开始,下降 100px 到 20% alpha 的绿色。看起来波浪基本上向下消失。我通过从我线上每个点的 y 位置开始绘制一个 1px 宽 x 100px 高的渐变来做到这一点。
这是我的绘图函数中的代码。
void *do_draw(void *ptr)
{
/*** Prepare SIGALRM ***/
siginfo_t info;
sigset_t sigset;
sigemptyset(&sigset);
sigaddset(&sigset, SIGALRM);
while(1)
{
while(sigwaitinfo(&sigset, &info) > 0)
{
currently_drawing = 1;
int width, height;
gdk_threads_enter();
gdk_drawable_get_size(pixmap, &width, &height);
gdk_threads_leave();
/*** Create surface to draw on ***/
cairo_surface_t *cst = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height);
cairo_t *cr = cairo_create(cst);
/*** Draw stuff ***/
static int i = 0;
++i; i = i % 800;
cairo_set_source_rgba (cr, .0, .0, .0, 1);
cairo_paint(cr);
int j = 0;
for (j = 0; j < 799; ++j)
{
double y = (double)(height + sine[j]) / 2;
cairo_pattern_t *pat1;
pat1 = cairo_pattern_create_linear(j, y, j, y + 100);
cairo_pattern_add_color_stop_rgba(pat1, 0.1, 0, 1, 0, 1);
cairo_pattern_add_color_stop_rgba(pat1, 0.9, 0, 1, 0, 0.2);
cairo_rectangle(cr, j, y, j, y + 100);
cairo_set_source(cr, pat1);
cairo_fill(cr);
cairo_pattern_destroy(pat1);
}
cairo_destroy(cr);
gdk_threads_enter();
cairo_t *cr_pixmap = gdk_cairo_create(pixmap);
cairo_set_source_surface(cr_pixmap, cst, 0, 0);
cairo_paint(cr_pixmap);
cairo_destroy(cr_pixmap);
gdk_threads_leave();
cairo_surface_destroy(cst);
currently_drawing = 0;
}
}
}
我现在得到的结果只是一条 20% alpha 绿色 100px 粗线,但它确实遵循我的坐标。我如何让这个渐变起作用?我不明白梯度空间是如何工作的。
最佳答案
我把它变成了一些可以实际编译和测试的独立代码,然后注意到你对 cairo_rectangle() 的调用是错误的。此函数的参数是:
- x
- 是
- 宽度
- 高度
你正在传入:
- j
- 是
- j
- y + 100
因此,较大的值会导致使用越来越大的矩形。我假设您需要这些参数:
- j
- 是
- 1
- 100
作为引用,这是我的代码:
#include <cairo.h>
#include <math.h>
int main(void)
{
int width = 800, height = 800;
int sine[800];
int k;
for (k = 0; k < 800; k++) {
sine[k] = height * sin(k*M_PI/180);
}
/*** Create surface to draw on ***/
cairo_surface_t *cst = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height);
cairo_t *cr = cairo_create(cst);
/*** Draw stuff ***/
static int i = 0;
++i; i = i % 800;
cairo_set_source_rgba (cr, .0, .0, .0, 1);
cairo_paint(cr);
int j = 0;
for (j = 0; j < 799; ++j)
{
double y = (double)(height + sine[j]) / 2;
cairo_pattern_t *pat1;
pat1 = cairo_pattern_create_linear(j, y, j, y + 100);
cairo_pattern_add_color_stop_rgba(pat1, 0.1, 0, 1, 0, 1);
cairo_pattern_add_color_stop_rgba(pat1, 0.9, 0, 1, 0, 0.2);
cairo_rectangle(cr, j, y, 1, 100);
cairo_set_source(cr, pat1);
cairo_fill(cr);
cairo_pattern_destroy(pat1);
}
cairo_destroy(cr);
cairo_surface_write_to_png(cst, "t.png");
cairo_surface_destroy(cst);
return 0;
}
关于c - (C + GTK + Cairo) 无法使线性渐变起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20725606/