Last active
November 28, 2022 22:43
-
-
Save cloudwu/766bccc60c254f9cc2abfa397bcff2ea to your computer and use it in GitHub Desktop.
sample for stb truetype
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#define HEIGHT 24 | |
#define STB_TRUETYPE_IMPLEMENTATION | |
#define STBTT_STATIC | |
// gcc -Wall -Wno-unused-function -g ttfont.c -o ttfont.exe | |
// https://github.com/nothings/stb/blob/master/stb_truetype.h | |
#include "stb_truetype.h" | |
unsigned char ttf_buffer[1<<25]; | |
#define MAXUNICODE 0x10FFFF | |
static int | |
utf8_decode(const char *o) { | |
static const unsigned int limits[] = {0xFF, 0x7F, 0x7FF, 0xFFFF}; | |
const unsigned char *s = (const unsigned char *)o; | |
unsigned int c = s[0]; | |
unsigned int res = 0; /* final result */ | |
if (c < 0x80) /* ascii? */ | |
res = c; | |
else { | |
int count = 0; /* to count number of continuation bytes */ | |
while (c & 0x40) { /* still have continuation bytes? */ | |
int cc = s[++count]; /* read next byte */ | |
if ((cc & 0xC0) != 0x80) /* not a continuation byte? */ | |
return -1; /* invalid byte sequence */ | |
res = (res << 6) | (cc & 0x3F); /* add lower 6 bits from cont. byte */ | |
c <<= 1; /* to test next bit */ | |
} | |
res |= ((c & 0x7F) << (count * 5)); /* add first byte */ | |
if (count > 3 || res > MAXUNICODE || res <= limits[count]) | |
return -1; /* invalid byte sequence */ | |
s += count; /* skip continuation bytes read */ | |
} | |
return res; | |
} | |
int | |
main() { | |
stbtt_fontinfo font; | |
int i,j; | |
int c = utf8_decode("中"); | |
fread(ttf_buffer, 1, 1<<25, fopen("c:/windows/fonts/msyh.ttc", "rb")); | |
stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0)); | |
float scale = stbtt_ScaleForPixelHeight(&font, HEIGHT); | |
int x0,y0,x1,y1; | |
int ascent,baseline, decent; | |
stbtt_GetFontVMetrics(&font, &ascent,&decent,0); | |
baseline = (int) (ascent*scale); | |
int height = (int) ((ascent - decent)*scale); | |
printf("ascent = %d, decent = %d, baseline = %d, height = %d\n", ascent, decent, baseline, height); | |
stbtt_GetCodepointBitmapBox(&font, c, scale, scale, &x0, &y0, &x1, &y1); | |
printf("x0=%d y0=%d x1=%d y1=%d\n", x0, y0, x1, y1); | |
int w = x1-x0; | |
int h = y1-y0; | |
unsigned char bitmap[h][w]; | |
stbtt_MakeCodepointBitmap(&font, &bitmap[0][0], w,h, w, scale, scale, c); | |
for (j=0; j < h; ++j) { | |
for (i=0; i < w; ++i) { | |
putchar(" .:ioVM@"[bitmap[j][i]>>5]); | |
} | |
putchar('\n'); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment