如何使用 cairo 创建圆形阴影效果?

fos*_*dom 5 python cairo

我试图通过给绘图一个微妙的阴影效果来增强我的应用程序的图形外观。我正在使用 python 和 cairo 绘图。

使用下面的示例代码,我可以用如图所示的图片绘制一个外圆和一个内圆。

图片

我想要做的是用阴影效果替换那个外圆。

我想我需要使用线性梯度或径向梯度,但我找不到一个很好的例子来实现我想要实现的目标。

有人请指出我正确的方向吗?

from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GdkPixbuf

import cairo
import math

class MyWindow (Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title='MyWindow')

        darea = Gtk.DrawingArea()
        darea.connect('draw', self.on_draw)
        self.add(darea)

        self.width, self.height = self.get_size()

        filename = "/usr/share/backgrounds/Thingvellir_by_pattersa.jpg"

        if self.width > self.height:
            self.width = self.height
        else:
            self.height = self.width

        self.width = self.width
        self.height = self.height

        self.pixbuf = GdkPixbuf.Pixbuf.new_from_file(filename)
        self.pixbuf = self.pixbuf.scale_simple(self.width, self.width, GdkPixbuf.InterpType.BILINEAR)

    def on_draw(self, widget, cr):

        w = self.width
        h = self.height

        # draw outer circle
        cr.translate(w/2, h/2)
        cr.set_line_width(10)

        cr.set_source_rgb(0.7, 0.2, 0.0)
        cr.arc(0, 0, w/2, 0, 2*math.pi)
        cr.stroke_preserve()
        cr.stroke()

        # now reset the origin and set the picture to be the source
        cr.translate(-w/2, -h/2)

        Gdk.cairo_set_source_pixbuf(cr, self.pixbuf, 0, 0)

        # now reset the origin again and this time clip the pixbuf 
        cr.translate(w/2, h/2)

        cr.arc(0, 0, w/2.2, 0, 2*math.pi) # was 2.2
        cr.stroke_preserve()
        cr.clip()
        cr.paint()

win = MyWindow()
win.connect('delete-event', Gtk.main_quit)
win.show_all()
Gtk.main()
Run Code Online (Sandbox Code Playgroud)

使用 Ubuntu 14.04 - Gtk+3.10,python3