Friday, May 8, 2015

Coordinate system for 2D computer graphics


Computers have a peculiar way to orient the axis of their coordinate system. It looks like this:



Basics

This means that the Upper-Left corner of an image or a window is (0,0).  In this type of programming, the unit along the axes is the pixel. When you create images, try using common image formats such as 800X480, or go for a square image of size 600X600.

With the graphics.py library, you can create a 800 pixels wide by 480 pixels high image using:

 mywindow = GraphWin( "Window Name", 800, 600 )




Software engineer's tip (Advanced)

It is good practice to define your width and your height as variable instead of coding them directly in the window creation call (see above). For example:

height = 480
width  = 800

mywindow = GraphWin( "Window Name", width, height )

The great thing about this is that you may now change the size of your image and everything may be set to scale with its new size. For example, you can always find the centre of your image with the following:

midpoint = Point( width * 0.5, height * 0.5 )

Without defining your dimensions, you would need to keep track of all details and change each of them. With relative coordinates, you may rescale an image simply by changing two values.

No comments:

Post a Comment