Skip to content

Instantly share code, notes, and snippets.

@mmmunk
Last active September 9, 2022 09:30
Show Gist options
  • Save mmmunk/e6035d7a3c3d7906bbe960d2b9e4e0a1 to your computer and use it in GitHub Desktop.
Save mmmunk/e6035d7a3c3d7906bbe960d2b9e4e0a1 to your computer and use it in GitHub Desktop.
New way of scaling images using pixbuf and gtk
#!/usr/bin/env python3
# https://discourse.gnome.org/t/scaling-images-with-cairo-is-much-slower-in-gtk4/7701
# https://blog.gtk.org/2018/03/16/textures-and-paintables/
import gi
gi.require_version("Gtk", "4.0")
gi.require_version("Gdk", "4.0")
gi.require_version("GdkPixbuf", "2.0")
from gi.repository import Gtk, Gdk, GdkPixbuf
def clicked(btn):
# btn.img.scale *= 1.5
btn.img.scale *= 0.8
btn.img.queue_resize()
def build_ui(app):
win = Gtk.Window()
win.set_default_size(500, 500)
win.set_application(app)
box = Gtk.Box()
win.set_child(box)
btn = Gtk.Button()
btn.set_label("Scale")
box.append(btn)
btn.connect('clicked', clicked)
scrolled_win = Gtk.ScrolledWindow()
box.append(scrolled_win)
img = MyWidget("/home/thomas/Pictures/14MB Helmcken_House.jpeg")
img.set_vexpand(True)
img.set_hexpand(True)
img.set_valign(Gtk.Align.CENTER)
img.set_halign(Gtk.Align.CENTER)
scrolled_win.set_child(img)
btn.img = img
win.present()
class MyWidget(Gtk.Widget):
def __init__(self, path, *args, **kwargs):
super().__init__(*args, **kwargs)
self.texture = Gdk.Texture.new_from_filename(path)
# self.pixbuf = GdkPixbuf.Pixbuf.new_from_file(path)
# self.texture = Gdk.Texture.new_for_pixbuf(self.pixbuf)
self.scale = 1
def do_snapshot(self, snapshot):
width = self.texture.get_intrinsic_width() * self.scale
height = self.texture.get_intrinsic_height() * self.scale
self.texture.snapshot(snapshot, width, height)
def do_get_request_mode(self):
return Gtk.SizeRequestMode.CONSTANT_SIZE
def do_measure(self, orientation, for_size):
if orientation == Gtk.Orientation.HORIZONTAL:
width = self.texture.get_intrinsic_width() * self.scale
return (width, width, -1, -1)
else:
height = self.texture.get_intrinsic_height() * self.scale
return (height, height, -1, -1)
def main():
app = Gtk.Application()
app.connect("activate", build_ui)
app.run()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment