Adjusting a scene after resizing the window

Cinder applications can respond to resizing the window by implementing the resize event. This method takes a ci::app::ResizeEvent parameter with information about the event.

Getting ready

If your application doesn't have a resize method, implement one. In the application's class declaration, add the following line of code:

void resize( ResizeEvent event );

In the method's implementation, you can use the ResizeEvent parameter to find information about the window's new size and format.

How to do it…

We will learn how to work with the ci::app::ResizeEvent parameter to respond to window resize events. Perform the following steps to do so:

  1. To find the new size of the window, you can use the getSize method which returns a ci::Vec2iwith object, the window's width as the x component, and the height as the y component.
    Vec2i windowSize = event.getSize();

    The getWidth and getHeight methods both return int values with the window's width and height respectively, for example:

    int width = event.getWidth();
    int height = event.getHeight();
  2. The getAspectRatio method returns a float value with the aspect ratio of the window, which is the ratio between its width and height:
    float ratio = event.getAspectRatio();
  3. Any element on screen that needs adjusting must use the new window size to recalculate its properties. For example, to have a rectangle that is drawn at the center of the window with a 20 pixel margin on all sides, we must first declare a ci::Rectf object in the class declaration:
    Rect frect;

    In the setup we set its properties so that it has a 20 pixel margin on all sides from the window:

    rect.x1 = 20.0f;
    rect.y1 = 20.0f;
    rect.x2 = getWindowWidth() – 20.0f;
    rect.y2 = getWindowHeight() – 20.0f;
  4. To draw the rectangle with a red color, add the following code snippet to the draw method:
    gl::color( Color( 1.0f, 0.0f, 0.0f ) );
    gl::drawSolidRect( rect );
  5. In the resize method, we must recalculate the rectangle properties so that it resizes itself to maintain the 20 pixel margin on all sides of the window:
    rect.x1 = 20.0f;
    rect.y1 = 20.0f;
    rect.x2 = event.getWidth() – 20.0f;
    rect.y2 = event.getHeight() – 20.0f;
  6. Run the application and resize the window. The rectangle will maintain its relative size and position according to the window size.
    How to do it…

How it works…

A Cinder application responds internally to the system's window resize events. It will then create the ci::app::ResizeEvent object and call the resize method on our application's class. This way Cinder creates a uniform way of dealing with resize events across the Windows and Mac platforms.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.103.204