单击时更改 PictureBox 图像
Change PictureBox image onClick
我有 5 个 PictureBox,我想在单击每个 PictureBox 时更改图像。
例如,如果 pictureBox1 上显示的图像是“_1”,当我单击它时,图像应该变为“_1x”,反之亦然。我的 if 子句中的代码从未执行,我不知道为什么。
这是我的代码:
private void Form1_Load(object sender, EventArgs e)
{
pb1.Image = Properties.Resources._1;
pb2.Image = Properties.Resources._2;
pb3.Image = Properties.Resources._3;
pb4.Image = Properties.Resources._4;
pb5.Image = Properties.Resources._10;
}
private void pb1_Click(object sender, EventArgs e)
{
if (pb1.Image == Properties.Resources._1)
{
pb1.Image = Properties.Resources._1x;
}
else { pb1.Image = Properties.Resources._1; }
}
在将图像附加到 Picturebox 之前,您需要保留对图像的本地引用,否则它总是会创建新对象,因此比较失败。
试试这个:
public partial class Form1 : Form
{
Bitmap img1 = Properties.Resources._1;
Bitmap img2 =Properties.Resources._2;
Bitmap img3 = Properties.Resources._3;
Bitmap img4 = Properties.Resources._4;
Bitmap img10 = Properties.Resources._10;
Bitmap img1x = Properties.Resources._1x
public Form1()
{
InitializeComponent();
pb1.Image = img1; //assign image1 to picturebox here
pb2.Image = img2;
pb3.Image = img3;
pb4.Image = img4;
pb10.Image = img10;
}
private void pb1_Click(object sender, EventArgs e)
{
if (pb1.Image == img1)
{
pb1.Image = img1x ;
}
else { pb1.Image = img1; }
}
}
我有 5 个 PictureBox,我想在单击每个 PictureBox 时更改图像。 例如,如果 pictureBox1 上显示的图像是“_1”,当我单击它时,图像应该变为“_1x”,反之亦然。我的 if 子句中的代码从未执行,我不知道为什么。
这是我的代码:
private void Form1_Load(object sender, EventArgs e)
{
pb1.Image = Properties.Resources._1;
pb2.Image = Properties.Resources._2;
pb3.Image = Properties.Resources._3;
pb4.Image = Properties.Resources._4;
pb5.Image = Properties.Resources._10;
}
private void pb1_Click(object sender, EventArgs e)
{
if (pb1.Image == Properties.Resources._1)
{
pb1.Image = Properties.Resources._1x;
}
else { pb1.Image = Properties.Resources._1; }
}
在将图像附加到 Picturebox 之前,您需要保留对图像的本地引用,否则它总是会创建新对象,因此比较失败。
试试这个:
public partial class Form1 : Form
{
Bitmap img1 = Properties.Resources._1;
Bitmap img2 =Properties.Resources._2;
Bitmap img3 = Properties.Resources._3;
Bitmap img4 = Properties.Resources._4;
Bitmap img10 = Properties.Resources._10;
Bitmap img1x = Properties.Resources._1x
public Form1()
{
InitializeComponent();
pb1.Image = img1; //assign image1 to picturebox here
pb2.Image = img2;
pb3.Image = img3;
pb4.Image = img4;
pb10.Image = img10;
}
private void pb1_Click(object sender, EventArgs e)
{
if (pb1.Image == img1)
{
pb1.Image = img1x ;
}
else { pb1.Image = img1; }
}
}