在窗口调整大小时保留 2D 对象的纵横比 [英] Preserve aspect ratio of 2D object on window resize

查看:25
本文介绍了在窗口调整大小时保留 2D 对象的纵横比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要在窗口内显示二维矩形的 Windows (XP) 应用程序.矩形不得被剪裁(即必须始终完全位于视口内),并且必须在调整大小时保持其纵横比.目前,处理布局的方法会扭曲矩形的纵横比以匹配窗口.我希望矩形缩放到窗口并在窗口中居中(同样,没有剪裁).方法如下.lWinDist 和 lMaxDepth 是要显示的矩形的宽度和高度(以 48 英寸为单位,如果重要的话):

I have a Windows (XP) application which needs to display a two-dimensional rectangle within a window. The rectangle must not be clipped (i.e. must always lie completely within the viewport), and must preserve its aspect ratio on resize. Currently, the method which handles layout distorts the aspect ratio of the rectangle to match the window. I want the rectangle to scale to the window and be centered in the window (again, without clipping). The method as it stands is below. lWinDist and lMaxDepth are the width and height of the rectangle to be displayed (in 48ths of an inch, if it matters):

void CRoRRecView::RedoLayout( long lWinDist, long lMaxDepth )
{
    CDC* pDC = GetDC() ;

    if ( pDC != NULL )
    {
        m_lWinDist = lWinDist;
        GetClientRect( m_rectClient ) ;
        int nClientWidth = m_rectClient.Width();
        int nClientHeight = m_rectClient.Height();
        glViewport( 0, 0, nClientWidth, nClientHeight );

        glMatrixMode( GL_PROJECTION);
        glLoadIdentity();

        m_fWinXDist = (float) lWinDist ;
        m_fWinYDist = lMaxDepth ;
        m_fAspectRatio = m_fWinXDist / m_fWinYDist;

        glOrtho(0.0, m_fWinXDist, 0.0, m_fWinYDist, -1, 1 ) ;

        glRotatef(180.0, 0,1,0); 
        glTranslatef( (float)(-1 * lWinDist),0,0 ); // Translate across the x axis

        glMatrixMode( GL_MODELVIEW );
        glLoadIdentity();

        ReleaseDC( pDC ) ;
    }
}

推荐答案

这个应该按预期扩展:

// g++ main.cpp -lglut -lGL
#include <GL/glut.h>

void display()
{
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    double w = glutGet( GLUT_WINDOW_WIDTH );
    double h = glutGet( GLUT_WINDOW_HEIGHT );
    double ar = w / h;
    glOrtho( -2 * ar, 2 * ar, -2, 2, -1, 1);

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    glColor3ub( 255, 0, 0 );
    glBegin( GL_QUADS );
    glVertex2i( -1, -1 );
    glVertex2i(  1, -1 );
    glVertex2i(  1,  1 );
    glVertex2i( -1,  1 );
    glEnd();

    glutSwapBuffers();
}

int main( int argc, char **argv )
{
    glutInit( &argc, argv );
    glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE );
    glutInitWindowSize( 640, 480 );
    glutCreateWindow( "Aspect Ratio" );
    glutDisplayFunc( display );
    glutMainLoop();
    return 0;
}

这篇关于在窗口调整大小时保留 2D 对象的纵横比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆