随机位图将数字转换为资源 ID
Posted
技术标签:
【中文标题】随机位图将数字转换为资源 ID【英文标题】:random bitmaps covert number to resource ID 【发布时间】:2013-04-27 02:47:54 【问题描述】:我正在尝试同时显示 2 个随机掷骰子。我知道我需要将模具编号转换为资源 ID,但如何?这是我到目前为止的代码......
什么是编码的好方法?
void CMFCApplication5Dlg::OnBnClickedButton1()
// randomize random number generator using current time
srand( (unsigned)time( NULL ) );
// pick random die values
int die1 = 1 + rand() % 6; // first die roll
int die2 = 1 + rand() % 6; // second die roll
pPCAvatar = (CStatic *) GetDlgItem(PC_AVATAR);
pIDCPicture = (CStatic *) GetDlgItem(IDC_PICTURE2);
//image for the avatar
CString Image1;
CString Image2;
CString Image3;
CString Image4;
CString Image5;
CString Image6;
//initialize entity from the constructor
Image1 = "pcture1.bmp"; // die face # 1
Image2 = "pcture2.bmp"; // die face # 2
Image3 = "pcture3.bmp"; // die face # 3
Image4 = "pcture4.bmp"; // die face # 4
Image5 = "pcture5.bmp"; // die face # 5
Image6 = "pcture6.bmp"; // die face # 6
// TODO: Add your control notification handler code here
【问题讨论】:
【参考方案1】:一种方法是使用switch/case
语句。
CString dieImage;
switch(dieValue)
case 0:
dieImage = "filename1";
break;
case 1:
dieImage = "filename2";
break;
// Rest of case statements
另一种方法是使用数组。
const CString dieImages[6] =
"filename1",
"filename2",
"filename3",
"filename4",
"filename5",
"filename6"
;
const CString& dieImage = dieImages[dieValue];
如果你想处理多个值,你可以把它放到一个函数中,使数组成为一个静态成员变量
const CString& GetDieImage(int dieValue) const
return dieImages[dieValue];
就这样称呼吧
const CString& dieImage1 = GetDieImage(dieValue1);
const CString& dieImage2 = GetDieImage(dieValue2);
要使用数组来管理图像名称,您可以将代码更改为如下所示。
void CMFCApplication5Dlg::OnBnClickedButton1()
static const CString dieImages[6] =
"filename1",
"filename2",
"filename3",
"filename4",
"filename5",
"filename6"
;
// pick random die values
const int die1 = 1 + rand() % 6; // first die roll
const int die2 = 1 + rand() % 6; // second die roll
const CString die1image = dieImages[die1];
const CString die2image = dieImages[die2];
// ... rest of your code goes here ...
【讨论】:
我没有多重人格,但我有。如果您能指出您遇到的具体问题,I 和 I 将非常乐意更新我们的答案。 我们使用来自您问题的源代码更新了我们的答案。希望这能让您顺利上路。 只是一个简短的说明。熟悉const-correctness。这是一件好事! filename 是名称位图文件或资源 ID(如果您使用字符串作为资源 ID)。否则将CString
更改为UINT
并将字符串更改为资源ID。加载图像调用CBitmap::LoadBitmap
。这是一个不同的问题,您需要研究如何在 MFC 和 Windows 中加载和使用资源。如果您仍然遇到问题,请在新问题中发布另一个问题并参考您的问题。以上是关于随机位图将数字转换为资源 ID的主要内容,如果未能解决你的问题,请参考以下文章