Search code examples
iosopengl-esopengl-es-2.0texturesprojection

Draw 2D texture without scaling?


I have just started playing with OpenGL ES 2.0, I managed to draw a 256x256 image and fill the entire viewport(320x460 in size). the image is scaled, as the screenshot shown below, but this is not desired, what I want is drawing the image in its original size from a specified 2D coordinate, say, from coordinate(10, 10) to coordinate(266, 266), looks like I need some kind of projection, but I don't know much about projection and I don't know how to start with it.

Any advice will be greatly appreciated.

EDIT

I just found this, and now I know it is because that the vertices I specified fill the entire viewport. now my question would be how do I map my image to the texture coordinate system? How do I calculate the X and Y coordinates of each of the 4 vertices so the image can fit just right on the texture surface without being scaled?

EDIT2

Thank you so much, @Slartibartfast, it is just that easy, I feel so dumb that I didn't get it right at the first place.

In case someone else needs this, the following are the vertices I specified to draw that little cute donkey from the upper left corner:

typedef struct {
    float position[2];
    float textureCoor[2];
} Vertex;

const Vertex vertices[] = {
    {{-1, 1}, {0, 0}},
    {{0.6, 1}, {1, 0}},
    {{0.6, -0.113}, {1, 1}},
    {{-1, -0.113}, {0, 1}},
};

const GLubyte indices[] = {
    0, 1, 2,
    2, 3, 0
};

enter image description here


Solution

  • As far as I can see. If you want to map the image exactly to the screen, the vertices you need to specify must be scaled accordingly.

    You have used coordinates spanning from -1 to 1 in both X and Y dimensions. Now this specifies the entire screen dimensions, which you have access to when you specify viewport. Let the screen dimensions are sw and sh, and image dimensions are tw and th.

    Since the width of the screen (sw) in terms of vertice coordinates is 2 (-1 to 1), width covered by image will be 2*tw/sw. Similarly height is 2*th/sh.

    Now you can specify your vertices to go from (-1,-1) to (-1 + 2*tw/sw, -1 + 2*th/sh), this will keep the image scaled and draw at the top left corner.