You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用C#实现点击按钮将图片随机放置在WinForm表格指定单元格

实现方案

核心逻辑:3列表格每列有3个单元格,每次点击按钮时,每列随机选中2个单元格用黑色矩形覆盖,总共生成6个遮罩层。

1. 调整窗体类全局定义

把随机数实例、遮罩列表、表格基础参数提到窗体类级别,避免每次点击重复创建,同时方便统一管理:

public partial class Form1 : Form
{
    // 全局随机数实例,避免短时间多次点击生成重复随机结果
    private readonly Random _rand = new Random();
    // 存储所有生成的遮罩控件,方便每次点击前清空
    private readonly List<PictureBox> _maskList = new List<PictureBox>();
    
    // --- 以下参数请根据你窗体里实际表格的尺寸和位置修改 ---
    // 表格左上角的X、Y坐标
    private const int TableStartX = 20;
    private const int TableStartY = 20;
    // 每个单元格的宽高(和你的black_rectangle.png尺寸一致)
    private const int CellWidth = 50;
    private const int CellHeight = 50;
    // 表格的列数、行数
    private const int ColCount = 3;
    private const int RowCount = 3;

    public Form1()
    {
        InitializeComponent();
    }
}

2. 实现按钮点击逻辑

每次点击先清空之前生成的遮罩,再逐列生成随机遮罩:

private void button1_Click(object sender, EventArgs e)
{
    // 先清空上一次生成的所有遮罩
    foreach (var mask in _maskList)
    {
        this.Controls.Remove(mask);
        mask.Dispose();
    }
    _maskList.Clear();

    // 逐列处理
    for (int col = 0; col < ColCount; col++)
    {
        // 生成当前列需要遮挡的2个不重复的行索引
        var hideRows = Enumerable.Range(0, RowCount)
                                .OrderBy(x => _rand.Next())
                                .Take(2)
                                .ToList();

        // 为每个需要遮挡的单元格生成遮罩
        foreach (int row in hideRows)
        {
            PictureBox mask = new PictureBox();
            // 加载项目资源里的黑色矩形图片
            mask.Image = Properties.Resources.black_rectangle;
            mask.SizeMode = PictureBoxSizeMode.StretchImage;
            mask.Width = CellWidth;
            mask.Height = CellHeight;
            // 计算遮罩的位置:列偏移+行偏移
            mask.Location = new Point(
                TableStartX + col * CellWidth,
                TableStartY + row * CellHeight
            );
            // 把遮罩加到窗体和列表里
            this.Controls.Add(mask);
            _maskList.Add(mask);
            // 把遮罩放到最上层,避免被表格挡住
            mask.BringToFront();
        }
    }
}

调整说明

  • 你需要先把black_rectangle.png导入到项目的资源文件里:右键项目→属性→资源→添加资源→添加现有文件,选中你的黑色矩形图片即可。
  • 代码里的TableStartX、TableStartY、CellWidth、CellHeight请根据你窗体里实际表格的位置和单元格尺寸修改,你可以直接在窗体设计器里选中表格控件,查看属性栏里的Location和Size参数计算对应值。
  • 如果暂时不想导入图片资源,可注释掉mask.Image和mask.SizeMode两行,新增mask.BackColor = Color.Black;即可实现纯黑色遮罩效果。

内容的提问来源于stack exchange,提问作者tajir12457

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 19:15:07