New way of scaling images using pixbuf and gtk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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