using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace painter
{
public partial class Form1 : Form
{
Array values = Enum.GetValues(typeof(Color));
Random random = new Random();
public bool shouldpaint = false;
public Form1()
{
InitializeComponent();
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
shouldpaint = true;
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
shouldpaint = false;
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (shouldpaint == true)
{
Graphics a = CreateGraphics();
Color randomColor = (Color)values.GetValue(random.Next(values.Length));
a.FillEllipse(new SolidBrush(randomColor), e.X, e.Y, 5, 5);
}
}
}
}
我正在尝试随机化SolidBrush(randomColor),这样当我移动鼠标时,它的颜色会相应地改变和绘制。我尝试了上面的代码,它给了我"一个未处理的类型' System.ArgumentException'发生在mscorlib.dll" 。你能检查一下我的随机化代码吗?在我添加该代码之前,它按照我预定的颜色按预期工作。
答案 0 :(得分:3)
如果您想要随机颜色,则必须创建随机数,并将其设置为Color Enum允许的最大最小值。
我认为最好忘记颜色枚举,而是使用旧的RGB构造函数。
Dim oRandomNumbers As New Random
Dim oColor as Color
oColor =Color.FromArgb(255, _
oRandomNumbers.Next(0, 256), _
oRandomNumbers.Next(0, 256), _
oRandomNumbers.Next(0, 256))
在c#中:
Random oRandomNumbers = new Random();
Color oColor = default(Color);
oColor = Color.FromArgb(255, oRandomNumbers.Next(0, 256),
oRandomNumbers.Next(0, 256),
oRandomNumbers.Next(0, 256));
编辑:正如@Enigmativity所说,256是它的独占上限,所以这将为你提供0到255之间的随机数