渲染图片
原理:
在一个矩形上面使用2D纹理贴图 从而显示图片
GL只识别bitmap 所以 jpeg png等格式要解码为bitmap 才能直接生成纹理->渲染
下面是Lite2D Text 渲染freetype生成的bitmap 字体的实现
void Text::draw()
{
if (this->_is_need_update)
{//need sync string
this->clear();
this->updateString();
this->_is_need_update = false;
}
if (this->_is_need_update_color)
{//need sync color
this->updateColor();
this->_is_need_update_color = false;
}
float width = 0;
float height = 0;
//deal with each font with string
for (int i = 0; i < _queue.size(); i++)
{
CharBitMap*bitmap = _queue[i];
glLoadIdentity();// vetex can work once
glBindTexture(GL_TEXTURE_2D, bitmap->texture_id);
// able alpha blend for the texture who has alpha
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//able opacity
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER, 0.0f);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
//start to render
glBegin(GL_QUADS);
//fix bug of transform of difference window size
Vec2 windowsize = Director::getInstance()->getWindowSize();
float xx = -1.0f; //position
float yy = -1.0f;
float scaleX = this->getGlobalScale().x; //scale
float scaleY = this->getGlobalScale().y;
float imageWidth = bitmap->width / windowsize.x;
float imageHeight = bitmap->height / windowsize.y;
float x, y;
if (i >= 1)
{
width += (_queue[i - 1]->width + _queue[i]->width) / 2.0f;
width += _fontsize*0.05f;
}
else
{
width += _queue[i]->width / 2.0f;
}
if (_queue[i]->_char <= 0xff)
{
height = _queue[i]->height / 2.0f + _fontsize*0.08F;
}
else
{
height = _fontsize / 2.0f;
}
height -= _fontsize *0.08;
// transform position with inner anchor point
x = (this->getGlobalPosition().x + width - _rect.x*_anchor.x) / windowsize.x * 2.0f
+ imageWidth - (0.5)*imageWidth * 2.0f;
y = (this->getGlobalPosition().y + height-_fontsize*_anchor.y*0.71// - (_anchor.y)*height * 2.0f)
)/windowsize.y * 2.0f + imageHeight - (0.5)*imageHeight * 2.0f;
xx += x;
yy += y;
//for different image has different Texcoord
float _coord2f[] = { 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f };
// glPushMatrix();
// transform the vertexs
glTexCoord2f(_coord2f[0], _coord2f[1]); glVertex2f(-imageWidth*scaleX + xx, -imageHeight*scaleY + yy);
glTexCoord2f(_coord2f[2], _coord2f[3]); glVertex2f(imageWidth*scaleX + xx, -imageHeight *scaleY + yy);
glTexCoord2f(_coord2f[4], _coord2f[5]); glVertex2f(imageWidth*scaleX + xx, imageHeight*scaleY + yy);
glTexCoord2f(_coord2f[6], _coord2f[7]); glVertex2f(-imageWidth*scaleX + xx, imageHeight*scaleY + yy);
//glPopMatrix();
glDisable(GL_BLEND);
glDisable(GL_ALPHA_TEST);
glEnd();
}
Node::draw();
}