Search code examples
c#opengldrawtexture2d

C# OpenGL Draw Stretched 2D texture (not resize!)


i am trying to draw a button from such texture: enter image description here And do this via that way:

    //sWidth, sHeight - stretched size.
    Size mySize = TheSprite.MyTexture.TextureSize;
    OpenGL.glBindTexture(OpenGL.TextureTarget.Texture2D, TheSprite.MyTexture.MyTextureID);
    OpenGL.glBegin(OpenGL.BeginMode.Quads);
    double x = (double)TheDestination.Left;
    double y = (double)TheDestination.Top;
    double s = (double)(TheSprite.MyLocation.Left + TheSource.Left) / (double)mySize.Width + sWidth;
    double t = (double)(TheSprite.MyLocation.Top + TheSource.Top) / (double)mySize.Height + sHeight;
    double x2 = (double)TheDestination.Right + sWidth;
    double s2 = (double)(TheSprite.MyLocation.Left + TheSource.Right) / (double)mySize.Width + sWidth;
    double y2 = (double)TheDestination.Bottom + sHeight;
    double t2 = (double)(TheSprite.MyLocation.Top + TheSource.Bottom) / (double)mySize.Height + sHeight;

    OpenGL.glColor4(TheModulation);

    OpenGL.glTexCoord2d(s, t2);
    OpenGL.glVertex2d(x, y2);
    OpenGL.glTexCoord2d(s, t);
    OpenGL.glVertex2d(x, y);
    OpenGL.glTexCoord2d(s2, t);
    OpenGL.glVertex2d(x2, y);
    OpenGL.glTexCoord2d(s2, t2);
    OpenGL.glVertex2d(x2, y2);
    OpenGL.glEnd();

But in my case, it looks like that: enter image description here

instead of something like this (same texture): enter image description here

How i should draw it for got it stretched, not resized in my case?


Solution

  • In this code

    OpenGL.glTexCoord2d(s, t2);
    OpenGL.glVertex2d(x, y2);
    OpenGL.glTexCoord2d(s, t);
    OpenGL.glVertex2d(x, y);
    OpenGL.glTexCoord2d(s2, t);
    OpenGL.glVertex2d(x2, y);
    OpenGL.glTexCoord2d(s2, t2);
    OpenGL.glVertex2d(x2, y2);
    

    you're mapping the corners of the texture to the corners of the button, like this:

    enter image description here

    enter image description here

    Since your texture is square and the button is rectangular, the texture is stretched horizontally to fit the width of the button. If you don't want the yellow frame to be stretched horizontally on the sides of the button, you need to use additional points when mapping the texture in order to stretch horizontally only the middle part of it (points 2-3-6-7). Like this:

    enter image description here

    enter image description here