使用数组改变picturebox的背景色

时间:2017-06-24 19:39:39

标签: c# mysql arrays image-processing arduino

我是c#编程的初学者。我打算用c#制作游戏。在这种情况下,当我点击图片框时我想换色。这是我的代码

         private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
    {
        int[] R = { 0, 255, 255, 34, 249,255 };
        int[] G = { 0, 255, 0, 235, 255 ,153};
        int[] B= { 255, 255, 0, 27, 40,51 };
        pictureBox1.BackColor = Color.FromArgb(R[this.index], G[this.index], B[this.index]);
        this.index++;
      }

此代码工作。当我点击图片框颜色改变。根据数组R,G,B可以得到6种颜色。在最后一种颜色后,我得到了这个消息.. 索引超出了数组的范围。

请有人告诉我这方面的解决方案。谢谢......

3 个答案:

答案 0 :(得分:2)

我找到了方法。

        int[] R = { 0, 255, 255, 34, 249, 255 };
        int[] G = { 0, 255, 0, 235, 255, 153 };
        int[] B = { 255, 255, 0, 27, 40, 51 };
        pictureBox2.BackColor = Color.FromArgb(R[this.index], G[this.index], B[this.index]);
        this.index++;
        if (this.index == 6)
        {
            this.index -= 6;

        }

在第6种颜色之后,我们可以得到第一种颜色

答案 1 :(得分:2)

请试试这个。 您需要考虑数组的长度。

private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
    int[] R = { 0, 255, 255, 34, 249,255 };
    int[] G = { 0, 255, 0, 235, 255 ,153};
    int[] B= { 255, 255, 0, 27, 40,51 };
    if(this.index <= (R.Length - 1) ||this.index <= (G.Length - 1) || this.index <= (B.Length - 1))
    {
        pictureBox1.BackColor = Color.FromArgb(R[this.index], G[this.index], B[this.index]);
        this.index++;
    } 
    else 
   {
       // Do nothing since you don't have colors
   }

}

答案 2 :(得分:0)

数组索引从0开始,它的长度为6,因此只需在代码中包装IF就像这样

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.sample</groupId>
    <artifactId>parent</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <modules>
        <module>child1</module>
        <module>child2</module>
    </modules>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>3.8.1</version>
                <scope>test</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <!--Global dependencies...-->
    </dependencies>

    <build>
        <pluginManagement>
            <!--Plugins...-->
        </pluginManagement>
    </build>
</project>