我一直在尝试制作一个简单的 wxWidgets 程序,它只有一个带有图片的按钮。我已经能够很容易地制作带有图像的按钮,但是在包含它时出现了我的问题。
到目前为止,我只能在运行时获取图像(图像必须与 .exe 文件位于同一文件夹中;否则,我会收到错误 2:系统找不到指定的文件).使用这种方法,我没有任何问题——程序运行良好。然而,我想要做的是 #include 文件,以便它在编译时嵌入,这样它就不需要在运行时可用。
我试过 #including 文件(.png 和 .xpm),我也试过将它添加到资源包含中(这是在 Visual Studio 2017 上)。这些都不起作用——第一种方法仍然要求图像位于同一个文件夹中,而第二种方法在编译过程中失败了(据我所知,它无法读取 .xpm 文件)。
下面是相关代码,如果有帮助的话:
/*relevant includes*/
#include "happyFace.png" //this isn't working. the file is still needed
||
#include "happyFace.xpm" //ditto
/*I have also tried putting these lines in the resource includes.*/
/*code*/
wxInitAllImageHandlers();
wxBitmap bitmap("happyFace.xpm", wxBITMAP_TYPE_XPM); //only works in same directory at run-time
||
wxBitmap bitmap("happyFace.png", wxBITMAP_TYPE_PNG); //ditto
wxButton *button = new wxButton(this, ID_BMP_BUTTON);
button->SetBitmap(bitmap);
//the rest of the button programming and stuff
抱歉,如果我没有提供足够的信息;如有必要,我可以提供更多。我真的很感激任何帮助。谢谢!
最佳答案
两种可能性……数字 1 是最简单的。自从我编写我正在查看的代码以来已经有很长时间了,所以细节很模糊。
在 Visual Studio 的解决方案资源管理器中,将图像添加到
资源文件
中。假设资源的名称是sample.rc
。然后就可以像这样设置主图标了...SetIcon(wxICON(sample));
必须使用方法 1 才能使 MS Windows 资源管理器显示主图标。我不记得如何将 .rc 资源用于其他用途,但应该很容易弄清楚。
在我发现 VS 资源 (.rc) 文件之前,我就是这样做的。 “手动”将文件镜像编译到程序中。换句话说,编写一个程序来读取图像文件并在 .cpp 文件中生成逐位复制。然后将该 .cpp 编译到程序中。在这里,我将内存中的文件图像作为一个名为 dj::main_cursor 的对象。请注意,内存中版本是 .cur 文件的逐位拷贝。
dj::captured_file &c1file(dj::main_cursor); wxMemoryInputStream cistr(c1file.contents, c1file.size); cursor1 = wxCursor(wxImage(cistr, wxBITMAP_TYPE_CUR));
仅供引用,我定义了结构 dj::captured_file 如下:
struct captured_file { const char *name; const unsigned long size; const void *contents; captured_file(const char*fn, size_t sz, const void*c) : name(fn) , contents(c) , size(sz) {} };
另请参阅,Embedding PNG Images into Windows RC Files
我找到了一些其他文档。
Resources and Application Icon All applications using wxMSW should have a Windows resource file (.rc extension) and this file should include include/wx/msw/wx.rc file which defines resources used by wxWidgets itself.
Among other things, wx.rc defines some standard icons, all of which have names starting with the "wx" prefix. This normally ensures that any icons defined in the application's own resource file come before them in alphabetical order which is important because Explorer (Windows shell) selects the first icon in alphabetical order to use as the application icon which is displayed when viewing its file in the file manager. So if all the icons defined in your application start with "x", "y" or "z", they won't be used by Explorer. To avoid this, ensure that the icon which is meant to be used as the main application icon has a name preceding "wxICON" in alphabetical order.
关于c++ - wxWidgets 在编译时包含图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49060762/