天天看点

wxwidgets 界面编程如何使用 png 图片

wxwidgets 是跨平台的GUI C++库,相比MFC, 更易学,更易使用。

GUI编程会用到小图标,下面介绍一种将使用的png图标和编译

的 exe 文件打包到一起的办法

先使用VC编译下面的代码为一个 exe 文件,比如:convert.exe

#include <ctype.h>

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#ifndef PATH_MAX

#define PATH_MAX 1024

#endif

int useconst = 0;

int zeroterminated = 0;

int myfgetc(FILE *f)

{

int c = fgetc(f);

if (c == EOF && zeroterminated)

{

zeroterminated = 0;

return 0;

}

return c;

}

void process(const char *ifname, const char *ofname)

{

FILE *ifile, *ofile;

ifile = fopen(ifname, "rb");

if (ifile == NULL)

{

fprintf(stderr, "cannot open %s for reading/n", ifname);

exit(1);

}

ofile = fopen(ofname, "wb");

if (ofile == NULL)

{

fprintf(stderr, "cannot open %s for writing/n", ofname);

exit(1);

}

char buf[PATH_MAX], *p;

const char *cp;

if ((cp = strrchr(ifname, '/')) != NULL)

{

++cp;

} else {

if ((cp = strrchr(ifname, '//')) != NULL)

++cp;

else

cp = ifname;

}

strcpy(buf, cp);

for (p = buf; *p != '/0'; ++p)

{

if (!isalnum(*p))

*p = '_';

}

fprintf(ofile, "static %sunsigned char %s[] = {/n", useconst ? "const " : "", buf);

int c, col = 1;

while ((c = myfgetc(ifile)) != EOF)

{

if (col >= 78 - 6)

{

fputc('/n', ofile);

col = 1;

}

fprintf(ofile, "0x%.2x, ", c);

col += 6;

}

fprintf(ofile, "/n};/n");

fclose(ifile);

fclose(ofile);

}

void usage(void)

{

fprintf(stderr, "usage: bin2c [-cz] <input_file> <output_file>/n");

exit(1);

}

int main(int argc, char **argv)

{

while (argc > 3)

{

if (!strcmp(argv[1], "-c"))

{

useconst = 1;

--argc;

++argv;

} else if (!strcmp(argv[1], "-z"))

{

zeroterminated = 1;

--argc;

++argv;

} else {

usage();

}

}

if (argc != 3)

{

usage();

}

process(argv[1], argv[2]);

return 0;

}

然后运行 convert xxx.png xxx.cpp (convet 是刚编译好的 exe文件,xxx.png 就是程序使用的png文件,xxx.cpp就是输出文件)

打开xxx.cpp,你会看到这个png图片被转为了一个数组

最后只需要在wxwidgets程序中包含 输出的 xxx.cpp 使用

使用前先要   

// add png handler

    wxImage::AddHandler(new wxPNGHandler);

#define wxGetBitmapFromMemory(name) _wxGetBitmapFromMemory(name ## _png, sizeof(name ## _png)) // 定义一个宏来获取内存bitmap

...

#include "xxx.cpp"

...

// 比如现在我建一个菜单 用这个 png

wxMenuItem * about = new wxMenuItem(menuHelp,HELP_ABOUT,GetText("About"));

about->SetBitmap(wxGetBitmapFromMemory(xxx));