为布尔按钮加载各种图像

本文关键字:图像 加载 布尔 按钮 | 更新日期: 2023-09-27 18:17:53

我在运行时创建按钮,我想为每个值true和false添加一个图像,如果我有onOff按钮,true为绿色,false为红色。

我的问题是1. 如何加载图片以最适合此目的?2. 如何以正确的方式创建按钮?3.我使用相同的功能枚举按钮,如果它看起来很奇怪。4. 我敢肯定我做错了很多事,请指教。
foreach(p in properties){
if(p is bool){createBoolButton(p);}
//so on
string path;
string path2;
private Control createBoolButton(IProperty p) {
  countControls2 = 1;
  locationY = 10;
  int gbHeight = 2;
  radioButtonY = 10;
  IType pType = p.Type;
  var myP = new MyProperty(p, this);
  if (myP.Value != null) {
  }
  Panel gb = new Panel();
  gb.Location = new Point(locationY, nextLocationX);
  nextLocationX += rbWidth + 10;
  gb.Name = "groupBox" + p.Id;
  gb.Text = p.Id;
  gb.Tag = p;
  bool[] x = { true, false };
  foreach (var t in x) {
    RadioButton rb = new RadioButton();
    rb.Appearance = Appearance.Button;
    rb.Width = rbWidth;
    rb.Height = rbHeight;
    rb.Name = t.ToString();
    rb.Text = t.ToString();
    rb.Tag = t;
    countControls++;
    rb.Location = new Point(radioButtonY, radioButtonX);
    if (myP.Value != null && myP.Value.ToString().SafeEquals(rb.Text)) {
      rb.Checked = true;
    }
    radioButtonY += rbHeight;
    gb.Controls.Add(rb);
    rb.CheckedChanged += rb_CheckedChanged;
  }
  gb.Width = rbHeight * gbHeight + 20;
  gb.Height = rbWidth + 10;
  Controls.Add(gb);
  countControls2++;
  return gb;
}
  private void getimagesPath(EnumValue[] TypesArray) {
  foreach (var enumType in TypesArray) {
    string path = @"C:'Folder'" + enumType.Name + ".png";
    string path2 = @"C:'Folder'" + enumType.Name + "_checked.png";
    FileInfo fi = new FileInfo(path);
    FileInfo fi2 = new FileInfo(path2);
    if (!imagePaths.ContainsKey(enumType.Name) && !imagePaths.ContainsKey(enumType.Name + "_checked")) {
      if (fi.Exists && fi2.Exists) {
        imagePaths.Add(enumType.Name, path);
        imagePaths.Add(enumType.Name + "_checked", path2);
      }
    }
    else {
      if (!imagePaths.ContainsKey(enumType.Name)) {
        imagePaths.Add(enumType.Name, DEFAULT_IMAGE_PATH);
      }
    }
  }
}

为布尔按钮加载各种图像

您应该将checked imageunchecked image保存为项目中的Resources。只要查看Solution Explorer,您将看到在项目节点下的Properties节点下有一个Resources节点。双击该节点,您应该知道如何向该Resources添加图像。一旦向其中添加了图像,就可以轻松访问这些图像,如下面的代码所示。我假设您选中的图像被添加到名称为CheckedImageResources和未选中的图像被添加到名称为UncheckedImageResources:

//Here is your RadioButton CheckedChanged event handler to change to image accordingly.
private void rb_CheckedChanged(object sender, EventArgs e){
   RadioButton button = sender as RadioButton;
   button.Image = button.Checked ? Properties.Resources.CheckedImage : Properties.Resources.UncheckedImage;
}
  1. 我想在这种情况下你不需要图片。

  2. 创建按钮示例代码:

    Dim pnl as new Panel
    Dim btn as new Button
    btn.Name = "btn1"
    btn.Location = new Point(..., ...)
    pnl.Controls.Add(btn)
    
对不起,我不懂c#。