OpenTK使用 FreeType2渲染字母范例

OpenTK库的.Net Wrapping见http://www.codeproject.com/Articles/13296/Rendering-FreeType-2-with-OpenGL

    public class FTText
    {
        //public static extern int FT_Init_FreeType(out System.IntPtr lib);
        //public Bitmap bitmap;
        public byte[] expanded;
        public int width;
        public int height;
        public FTText()
        {
            //初始化库
            IntPtr libptr;
            if (Library.FT_Init_FreeType(out libptr)!=0)    return;
            int size = 50;

            IntPtr faceptr;

            if (Face.FT_New_Face(libptr, "J:\\GameProject\\GameProject\\Fonts\\Anonymous.ttf", 0, out faceptr)!=0)  return;
            Face face = (Face)Marshal.PtrToStructure(faceptr, typeof(Face));

            Face.FT_Set_Char_Size(faceptr, size << 6, size << 6, 96, 96);
            Face.FT_Set_Pixel_Sizes(faceptr, size, size);

            int index = Face.FT_Get_Char_Index(faceptr, ' ');
            if (Face.FT_Load_Glyph(faceptr, index, FT_LOAD_TYPES.FT_LOAD_DEFAULT)!=0)   return;

            //Convert the glyph to a bitmap
            System.IntPtr glyph;
            if (Glyph.FT_Get_Glyph(face.glyphrec, out glyph)!=0)    return;
            Glyph.FT_Glyph_To_Bitmap(out glyph, FT_RENDER_MODES.FT_RENDER_MODE_NORMAL, 0, 1);
            BitmapGlyph glyph_bmp = (BitmapGlyph)Marshal.PtrToStructure(glyph, typeof(BitmapGlyph));

            byte[] bmp = new byte[glyph_bmp.bitmap.width * glyph_bmp.bitmap.rows];
            Marshal.Copy(glyph_bmp.bitmap.buffer, bmp, 0, bmp.Length);

            //Next we expand the bitmap into an opengl texture 	    	
            width = next_po2(glyph_bmp.bitmap.width);
            height = next_po2(glyph_bmp.bitmap.rows);
            //expanded = bmp;
            expanded = new byte[2 * width * height];
            for (int j = 0; j < height; j++)
            {
                for (int i = 0; i < width; i++)
                {
                    expanded[2 * (i + j * width)] = expanded[2 * (i + j * width) + 1] =
                        (i >= glyph_bmp.bitmap.width || j >= glyph_bmp.bitmap.rows) ?
                        (byte)0 : bmp[i + glyph_bmp.bitmap.width * j];
                }
            }
            
            //expanded = null;
            bmp = null;	

             Dispose of these as we don't need
            Face.FT_Done_Face(faceptr);
            Library.FT_Done_FreeType(libptr);

        }
        internal int next_po2(int a)
        {
            int rval = 1;
            while (rval < a) rval <<= 1;
            return rval;
        }
    }



版权声明:本文为awinnerisyou原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。