[cairo] New user question. How do I fill inside of a curve?

Bertram Felgenhauer bertram.felgenhauer at googlemail.com
Wed Jan 2 12:49:13 PST 2008


Jody Winston wrote:
> I have a curve that I would like to have one fill color for the positive 
> half and another fill color for the negative side.  In other words, draw 
> a curve, draw a horizontal line at y = 0, fill everything above 0 with 
> one color and below with another color.
> 
> I'm able to clip the curve but I do not seem to be able to fill the 
> resulted curve.
[snip]
> Here's a snippet of the problem in Python:
> 
> def sawToothPath(context):
>    context.move_to(-100, -100)
>    context.line_to(100, 100)
> 
>    context.move_to(100, 100)
>    context.line_to(200, -200)
> 
>    context.move_to(200, -200)
>    context.line_to(300, 300)

up to here, sawToothPath(context) creates a path which can be stroked,
filled and the like.

>    context.stroke()

However, context.stroke() consumes the path - after this line, the path
is empty again. There's a function

     context.stroke_preserve()

that preserves the path.

> def sawTooth(context):
>    context.set_source_rgb(0, 0, 1)
>    context.save()
> 
>    context.save()
>    context.rectangle(-100, 0, 400, 300)
>    context.set_source_rgb(1, 0, 0)
>    context.restore()
>    context.clip()

Why the save/restore? Like stroke(), clip() consumes the path, and
besides, save()/restore() don't affect paths, so the above is
equivalent to

     context.rectangle(-100, 0, 400, 300)
     context.clip()

>    sawToothPath()
>    context.set_fill_rule(cairo.FILL_RULE_WINDING)
>    context.fill()
>    context.restore()
> 
>    return


Style note: It probably makes more sense to separate path creation
and drawing, that is, remove the context.stroke() from sawToothPath()
and then do

     sawToothPath()
     context.fill_preserve()
     context.source_rgb(0, 1, 0)
     context.stroke()

(I'd stroke after filling, so that the fill doesn't erase half of
the stroke.)

HTH,

Bertram


More information about the cairo mailing list