Jump to content
  • Advertisement
Sign in to follow this  

OpenGL pixel perfect 2d rectangles (code)

This topic is 4071 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I've been trying to draw rectangles so that they would begin and end at exactly the specified pixel locations. Despite my best efforts, OpenGL refuses to do this correctly and consistently across machines. At first I tried this, as recommended elsewhere: glTranslatef(0.375f, 0.375f, 0); But that didn't change anything. Here's a hack I threw together to solve the problem:
  void Render::initProjection() {
    glMatrixMode( GL_PROJECTION );

    glOrtho(0.0f, (float)(m_width),
	    0.0f, (float)(m_height),
	    -1.0f, 1.0f);

  void Render::initModelview() {
    glTranslatef(0.375f, 0.375f, 0);


void Render::start() {


void Render::finish() {

  // render rectangles and determine what kinds offsets we need to make them
  // pixel perfect on this machine.
  // (do this once at initialization)
  void Render::testOffsets() {

    // make sure the clear color is black
    glClearColor(0, 0, 0, 1.0f);


    // draw a filled rect
    glColor3f(1.0f, 0, 0);
    rectangle(10, 10, 10, 10);



    // check to see if pixels were drawn to the expected locations
    // and if they were not, tell the renderer it needs to use an offset
    // from now on.

    m_filledRectOffset = m_outlineRectOffset = vec2i(0,0);

    uint8 pixelColor = 0;
    glReadPixels( 19, 15, 1, 1, GL_RED, GL_UNSIGNED_BYTE, &pixelColor);
    if (!pixelColor)
      m_filledRectOffset[0] = 1;
    glReadPixels(15, 19, 1, 1, GL_RED, GL_UNSIGNED_BYTE, &pixelColor);
    if (!pixelColor)
      m_filledRectOffset[1] = 1;


void Render::rectangle( int x, int y, int w, int h, RectangleType rectType ) {
    vec2i offset = m_filledRectOffset;

    if (rectType == RECT_OUTLINE) {
      glPushAttrib( GL_POLYGON_BIT);
      glPolygonMode(GL_FRONT, GL_LINE);
      offset = m_outlineRectOffset;

    glVertex2i( x    , y );
    glVertex2i( x + w-1 + offset[0], y );
    glVertex2i( x + w-1 + offset[0], y + h-1 + offset[1] );
    glVertex2i( x      , y + h-1 + offset[1] );

    if (rectType == RECT_OUTLINE) {


Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!