sonist-gtk/ui/image.py

59 lines
1.4 KiB
Python
Raw Normal View History

2023-08-17 20:51:59 +08:00
#!/usr/bin/env python3
import gi, cairo, math
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GdkPixbuf
class ScaleImage(Gtk.Image):
def __init__(self, filepath):
Gtk.Image.__init__(self)
self.origin = GdkPixbuf.Pixbuf.new_from_file(filepath)
self.pixbuf = self.origin
self.width = self.origin.get_width()
self.height = self.origin.get_height()
self.set_from_pixbuf(self.origin)
def resize(self, width, height):
self.width = width
self.height = height
self.pixbuf = self.origin.scale_simple(width, height, GdkPixbuf.InterpType.BILINEAR)
self.set_from_pixbuf(self.pixbuf)
def set_radius(self, radius = 0):
w = self.width
h = self.height
surface = cairo.ImageSurface(cairo.Format.ARGB32, w, h)
ctx = cairo.Context(surface)
Gdk.cairo_set_source_pixbuf(ctx, self.pixbuf, 0, 0)
# 左上角 圆角
ctx.arc(radius, radius, radius, -math.pi, -math.pi / 2.)
ctx.line_to(w - radius, 0)
# 右上角 圆角
ctx.arc(w - radius, radius, radius, -math.pi / 2., 0)
ctx.line_to(w, -radius)
# 右下角 圆角
ctx.arc(w - radius, h - radius, radius, 0, math.pi / 2.)
ctx.line_to(radius, h)
# 左下角 圆角
ctx.arc(radius, h - radius, radius, math.pi / 2., math.pi)
ctx.close_path()
ctx.clip()
ctx.paint()
pixbuf = Gdk.pixbuf_get_from_surface(surface, 0, 0, w, h)
self.set_from_pixbuf(pixbuf)