python pygame what does font mean? - python-3.x

I am now studying an online pygame tutorial. However, I am not sure how it works when trying to place text on the screen. According to the official docs for pygame.font.Sysfont():
Return a new Font object that is loaded from the system fonts. The font will match the requested bold and italic flags. If a suitable system font is not found this will fall back on loading the default pygame font. The font name can be a comma separated list of font names to look for.
What is a font?
font = pygame.font.SysFont(None, 25)
# message to the user
def message_to_screen(msg,color):
screen_text = font.render(msg, True, color)
screen.blit(screen_text, [screen_width/2,screen_height/2])

Ok, here is the simplest explanation i can give you:
Modules such as Pygame are simple (or sometimes not that simple...) codes that add new features and functions to your normal built in python functions. This means that when you import a module you also inherent from that module all of its functions and classes. So for example, the normal python does not contain the function "draw"
pygame.draw.rect(arguments)
however when you import pygame, you inherent that function from the pygame code. allowing you to draw and develop a GUI for better programs.
Same is with objects. Python is an 'object orientated programming language". Objects are a type of data store that defines and structures your code. So for example, sprites in Pygame can be anything you want. Your sprite can be anything you want from a monkey, or a freaking mummy eating zombie, to a simple rectangle. To create the exact sprite you want with the right shape, color, rect, and image, you need to structure it with a class. A class is what will create the object for your sprite. Look at this here:
#Here is the class named 'Button' of type ' pygame.sprite.Sprite'
class Button(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
#Here we define the shape of the sprite. In the case it is a simple
#150 by 75 rectangle surface. The shape can also be an image or any
#or any geometric shape you want
self.image = pygame.Surface((150, 75))
#here we define the color of the sprite
self.image.fill(green)
#and here we make sure the sprite has a rect
self.rect = self.image.get_rect()
so as you see this class defines all what we need to create this simple sprite. Of course it can have many more variables to it depending on what the sprite is, but lets stick with something simple for now
Now the class stores this information in an object, to be used later. Like this:
MySpriteObject = Button()
simple enough i would say. so now you have a sprite object and can use pygames' many function to draw it on the screen, add interaction to it, group it, and a lot of other things.
so Finally you understand the idea of an object in python. Now to you're actual question.
What is a font?
Well a font is an object that you get when you import pygame. You don't have to do the class stuff at the top as the pygame module does that for you. Just create the object and use the function 'render'. So essentially it is an object that you can change two things in as you like. the font, and the size
MyFontObject = pygame.font.Font(#Font here, #size here)
If you make the Font argument None, then it will give you the default pygame font. Thats what I usually do. However, if you want to change the font, you can either download a font (usually a .ttf) and then type in its folder path in the Font argument, or you can use a font that you have on your computer. To do that instead of
MyFontObject = pygame.font.Font(#Font here,#size here)
you use
MyFontObject = pygame.font.SysFont(#Name of font here, #size here)
Where #Name of font here is, you can replace it by any font installed on your computer. To get a list of the names of fonts on your computer that pygame can identify:
pygame.font.get_fonts()
Ok, so that is how you create the font object. Now to rendering it.
Rendering the font uses the font object to change the shape and color of the text you want to display. Here is how its done
text = MyFontObject.render(#Your Text Here,#true or false,#color)
screen.blit(tex,t(#X axis,#Y axis))
Pretty self explanatory. Except for the #true or false i guess. That pretty much asks you if you want to use a technique that helps the text look less pixeled and square-like. If you provide true it will. If you dont the text will look awefull, so always keep it true.
So that's pretty much what i have to say. Here is a short summary:
1.) An object is a type of data store which stores different variables to structure and define your code. So therefore a font object is an object that defines the different things for a font, such as size and font type
2.) to create an object we use a class as shown above
3.) A font class is already there with the pygame module so you just have to call the font object straight away:
MyFontObject = pygame.font.Font(#filepath or None for the default pygame font,#size here)
or for a font that is installed on your system such as ariel (which can all be viewed with pygame.font.get_font())
MyFontObject = pygame.font.SysFont(#Name of system font here,#size here)
4.) To put this font object to use you render it:
text = MyFontObject.render(#Text here,#True or false,#color of text)
then normally blit it on the screen and call pygame.display.update
screen.blit(text,(#X axis,#Y axis)
pygame.display.update()
I hope this helps. I know I'm not the best explainer and I write too much, but you should read the summary at least.
P.S: Sorry for using sprites to explain classes and objects. I know I went of topic but it was just an example.

Related

Using vtkImageActor for adding mask to vtkImageViewer2

I am developing on an application based on VTK and GDCM for viewing medical (DICOM) images.
The application has three windows that respectively show XY, YZ and XZ orientations (axial, coronal and sagittal). This is similar to the 2D views here. I use vtkImageViewer2 for this. The voxel values of the DICOM images are passed on to an instance of vtkImageData. The instance of the vtkImageData is the passed on the to three instances of vtkImageViewer2 (let's use imageViewerXY, imageViewerYZ and imageViewerXZ). The orientation of each instance of vtkImageViewer2 is then set using SetSliceOrientationToXY(), SetSliceOrientationToYZ() and SetSliceOrientationToXZ(). Without the mask, I can see the slices, couple the windows and scroll through the images perfectly fine.
To add the mask so that it is shown in the three views, I use vtkImageActor. For the XY view, which is the default view, this works fine. I update the instance of vtkImageActor, which I call maskActorXY based on the mouse events of XY window as follows:
int extent[6];
imageViewerXY->GetImageActor->GetDisplayExtent(extent);
maskActorXY->SetDisplayExtent(extent);
maskActorXY->Update();
imageViewerXY->GetRenerer->Render();
Now, when I do the same for the other two windows so that I can see the 3D mask in the other two orientations, for example for the YZ orientation,
imageViewerYZ->GetImageActor->GetDisplayExtent(extent);
maskActorYZ->SetDisplayExtent(extent);
maskActorYZ->Update();
imageViewerYZ->GetRenerer->Render();
I get an error message that traces to vtkImageData and accessing pixel values outside of the extent set for the mask actor.
I have a limited familiarity with VTK, but looking at the source code of vtkImageViewer2 (see UpdateDisplayExtent() on line 341), I don't understand why pixel values out side of the specified display extent are requested from my instances of vtkImageActor that represent the mask.
I found a solution. Since I am not familiar with VTK, I may not be able to provide a clear explanation. All that I needed were the following two lines for each mask to force its mappers to face the camera:
maskActorYZ->GetMapper()->SetAtFocalPointOn();
maskActorYZ->GetMapper()->SliceFacesCameraOn();
(see [vtkImageMapper3D][1] class.)

Kivy rotation during movement

I'm struggling with how to properly implement simultaneous movement and rotation using Kivy (in python, not kv lang). My goal is to rotate an object so it's facing its destination then move it towards the destination using Animation. Using the code below I typically get movement in relation to the angle rotated instead of in relation to my general playing area. For example the animation without rotation might move an image to point [1,1] whereas with rotation of 180* the animation is moving the image to [-1,-1]. The image is properly rotated in this scenario, meaning it's facing the right way but going the wrong way.
My understanding is that the push/pop matrix functions should provide the appropriate context for the animation rather than the rotated element context. Because the PopMatrix function is happening in Canvas.after it seems like this has no effect - my animation is completed before the original Matrix is restored.
I'm lacking some key piece of information here that's causing a lot of headache. Can someone explain why the code below causes an image to move to (-1,-1) rather than the (1,1) indicated, and how to properly implement this?
I threw this code together as an example, my game code is far more complex. That's why I'm hoping for an explanation rather than a direct solution for my code. Thanks.
with self.image.canvas.before:
PushMatrix()
self.rot = Rotate()
self.rot.axis = (0, 0, 1)
self.rot.origin=self.center
self.rot.angle=180
with self.image.canvas.after:
PopMatrix()
self.anim = Animation(pos = (1,1), duration=1)
self.anim.start(self)
self.image.pos = self.pos
self.image.size = self.size
In case others are interested in how to make this work consistently - I've found that setting origin and angle on each frame, along with binding the image widget to any pos change on it's parent will ensure the widget moves with its parent and in the proper direction. I implemented that like this:
Instantiate the image like this:
with self.image.canvas.before:
PushMatrix()
self.rot = Rotate()
self.rot.axis = (0, 0, 1)
self.rot.origin=self.center
self.rot.angle = 0
with self.image.canvas.after:
PopMatrix()
Bind it like this:
self.bind(pos = self.binding)
def binding(self, *args):
self.image.center = self.center
self.image.size = self.size
On each frame call a function that does similar to the below.
self.rot.origin = self.center
self.rot.angle = getangle()#you can use a set angle or generate a new angle every frame
Rotate effectively changes the coordinate system used by the entire canvas, so after you've rotated by 180 degrees the position [1, 1] really is in the opposite direction to what it was before, as far as any canvas instruction is concerned.
I don't know what self.image is (maybe an Image widget?), but presumably whatever you see is something like a Rectangle drawn on its canvas, whose pos and size match those of the widget. When you update that pos and size, the Rectangle is positioned according to the current coordinate system, which is in the rotated frame.
Thinking about it, I'm not sure if there's a neat way to combine Rotate instructions with Kivy's high level widget coordinates in quite this way. Of course you can work around it in various ways, such as by accounting for the rotation when setting the position of the Rectangle, but that's kind of fiddly, and inconvenient when working with prebuilt widgets. You can also look at what the Scatter widget does to enable arbitrary transformations.
If you just want to rotate by 180 degrees, you can instead adjust the image being displayed, either before displaying it or by adjusting the tex_coords of the Rectangle to change the displayed orientation. However, this won't work for arbitrary rotations, which it looks like you may want.

Generate an image of all widgets within a scrollarea

BACKGROUND:
I have a python program that is being used by a number of engineers. It indicates the status of some piece of equipment under test.
I am using a QScrollArea() to contain a QGridLayout which is packed with alot of information.
bit_grid = QtGui.QGridLayout()
...
scroll = QtGui.QScrollArea()
info = QtGui.QWidget()
info.setLayout(bit_grid)
scroll.setWidget(info)
There are quite a few status indicators on the GUI and as such the scrollbar is used to ensure the GUI fits on one screen.
When an engineer want's to describe a failure what they are doing right now is taking multiple screenshot, one for each new displayed area of the ScrollArea. They are then stitched together to make one large image.
Is there a way to generate a png (or an img format) of the area that could be display within a ScrollArea?
Try this:
pixmap = QtGui.QPixmap.grabWidget(scroll)
pixmap.save('path/to/file.png', None, 100)
This snippet will take a snapshot of whatever is inside the scrollArea and save that as a png image to path/to/ folder as file.png
ok solved.
widget = self.scroll.widget()
pixmap = QtGui.QPixmap(widget.size())
widget.render(pixmap)
pixmap.save(filename, 'PNG', 100)
The key was to grab the widget that is in scroll as this could then be (virtually) rendered. The resultant pixmap could then be saved.

Add BullsEye to Image (changing pixels)

I am trying to add a target (bullseye) to an image without the use of importing python functions, it is proving to be rather difficult however I believe I need to define a circle through use of code. It should be done by changing the pixels as opposed to importing functions.
Thanks
Needs to be in the centre of an image
You will need to add more information here - how is your image represnted in Python? Normally for porduction code, dealing with images is done through 3rd party modules, each of which have a way to draw or change different pixels. If you are using none you have to define your image reading and writting code (or a way to display the image on the screen).
Anyway, doing all of that without any "importing" will be quite artificial, though feasible.
Maybe you should use pnm files which have a minimum of encoding required.
That said, you could represent the image in memory as a bytesarray object, and use math.sin and math.cos (you will have to import those, or resort to a "raytracing" approach which can render the circle based on x**2 + y * 2 = r ** 2 ) to draw your circle.

What manager is suggested for Gallery Manager?

I am working on implementing a gallery, I tried GridFieldManager for this, but the images of the thumbnail are not of same size. I sneaked through the gridfieldclass but there are no methods for making the cell size of each image constant.
Is it worth to use flowfieldmnager? When I tried overriding sublayout method for the above two managers it is not giving the desired reults.
Is it possible to sublayout flowfieldmanager?
Device : Blackberry 9780, OS 6.0
The below image is the desired result I am trying to get
I advice you to use a simple FlowFieldManager. But instead of BitmapField inside it, extend a Field to do the following:
setExtent to 1/4 of the Display width in the sublayout method
draw your own focus in the border of the image
draw your own borders and draw the image in the center of the field's extent

Resources