Created
July 2, 2017 22:24
-
-
Save infirit/22b147bcdcdc1ed4584f1f513fd1855e to your computer and use it in GitHub Desktop.
silly cairo surface scaling example (dd 2017-07-03 requires patched pycairo)
This file contains hidden or 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
| import gi | |
| gi.require_version("Gtk", "3.0") | |
| from gi.repository import Gtk | |
| import cairo | |
| class IconWindow(Gtk.Window): | |
| def __init__(self, *args, **kwargs): | |
| super().__init__(default_width=150, default_height=150, **kwargs) | |
| self.icon_name = "thunderbird-icon" | |
| self._image = Gtk.Image() | |
| self.grid = Gtk.Grid() | |
| self.add(self.grid) | |
| self.grid.add(self._image) | |
| self._icon_theme = Gtk.IconTheme.get_default() | |
| self.connect("style-set", self._on_style_set) | |
| self._set_icon() | |
| self.connect("delete-event", Gtk.main_quit) | |
| @property | |
| def device_scale(self): | |
| scale = self.get_scale_factor() | |
| return (scale, scale) | |
| def _get_icon_surface(self, icon_name, size=48): | |
| surface = self._icon_theme.load_surface( | |
| icon_name, size, 1, self.get_window(), | |
| Gtk.IconLookupFlags.FORCE_SIZE | |
| ) | |
| surface.set_device_scale(*self.device_scale) | |
| return surface | |
| def _set_icon(self): | |
| x_scale, y_scale = self.device_scale | |
| surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 48, 48) | |
| surface.set_device_scale(x_scale, y_scale) | |
| context = cairo.Context(surface) | |
| main_surface = self._get_icon_surface(self.icon_name) | |
| context.set_source_surface(main_surface, 0, 0) | |
| context.paint() | |
| mini_one = self._get_icon_surface(self.icon_name, 16) | |
| context.set_source_surface(mini_one, 1 / x_scale, 1 / y_scale) | |
| context.paint() | |
| mini_two = self._get_icon_surface(self.icon_name, 16) | |
| # Paint one pixel from the bottom | |
| height = surface.get_height() | |
| mini_height = mini_two.get_height() | |
| y = height / y_scale - mini_height / y_scale - 1 / y_scale | |
| print("height: %s / mini height: %s / y: %s" % (height, mini_height, y)) | |
| # Paint one pixel from the right | |
| width = surface.get_width() | |
| mini_width = mini_two.get_width() | |
| x = width / x_scale - mini_height / x_scale - 1 / x_scale | |
| print("width: %s / mini width: %s / x: %s" % (width, mini_width, x)) | |
| context.set_source_surface(mini_two, x, y) | |
| context.paint() | |
| self._image.set_from_surface(surface) | |
| def _on_style_set(self, *args, **kwargs): | |
| print(*args, **kwargs) | |
| my_win = IconWindow() | |
| my_win.show_all() | |
| Gtk.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment