Last active
June 4, 2019 22:23
-
-
Save olehermanse/bbb7a30e29c185b6577575b8e03252b7 to your computer and use it in GitHub Desktop.
Resizable high resolution hello world in pyglet - https://bitbucket.org/pyglet/pyglet/issues/249
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
'''Resizable hello world example which works on mac and windows | |
There are a few bugs / differences between pyglet on these platforms. | |
This example tries to work around those issues. | |
Based on: | |
https://bitbucket.org/pyglet/pyglet/issues/78/ | |
https://bitbucket.org/pyglet/pyglet/issues/248/ | |
...and a lot of trial and error. | |
''' | |
import pyglet | |
def font_size_from_height(height): | |
return height // 6 | |
class HelloWorldWindow(pyglet.window.Window): | |
def __init__(self): | |
width, height = 800, 600 | |
super(HelloWorldWindow, self).__init__( | |
width, height, caption='Text rendering example', resizable=True) | |
self.ratio = width / height | |
self.set_minimum_size(width // 2, height // 2) | |
self.label = pyglet.text.Label( | |
'Hello, world', | |
font_name='Times New Roman', | |
font_size=font_size_from_height(height), | |
anchor_x='center', | |
anchor_y='center') | |
self.on_resize(width, height) | |
def on_draw(self): | |
self.clear() | |
# Use viewport size to set the coordinate system: | |
pyglet.gl.glMatrixMode(pyglet.gl.GL_PROJECTION) | |
pyglet.gl.glLoadIdentity() | |
width, height = self.get_viewport_size() | |
pyglet.gl.glOrtho(0, width, 0, height, -1, 1) | |
pyglet.gl.glMatrixMode(pyglet.gl.GL_MODELVIEW) | |
# The glOrtho call is necessary for high resolution mac font rendering | |
# Start normal drawing: | |
self.label.draw() | |
def on_resize(self, w, h): | |
w = int(self.ratio * h) # Locked aspect ratio | |
self.width = w | |
self.height = h | |
# Don't use window dimensions for coordinate system, use viewport: | |
width, height = self.get_viewport_size() # May be scaled (on mac) | |
# Resize viewport (only necessary on windows): | |
pyglet.gl.glViewport(0, 0, max(1, width), max(1, height)) | |
# Resize font in label: | |
self.label.font_size = font_size_from_height(height) | |
# Center label: | |
self.label.x, self.label.y = width // 2, height // 2 | |
def main(): | |
window = HelloWorldWindow() | |
pyglet.app.run() | |
if __name__ == "__main__": | |
main() # main function ensures no variables are in global scope |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment