c# - C# Smooth Rainbow Fading 问题
问题描述
因此,我试图通过将不同的值添加到 RGB 并将标签设置为这些值来使这个具有非常平滑的彩虹渐变的文本标签,但我无法找到一种方法来停止启动整个过程的起始值!我知道这段代码很乱,而且还有一些不需要的东西,比如那个随机数。但它抛出错误“System.ArgumentException:'256'的值对'red'无效。'red'应该大于或等于0且小于或等于255。'”
int R = 0;
int G = 0;
int B = 0;
private void timer2_Tick(object sender, EventArgs e)
{
Random r = new Random();
int A = r.Next(255, 255);
R += 1;
if (R > 250)
{
G += 1;
R -= 1;
}
if (G > 250)
{
B += 1;
G -= 1;
}
if (B > 250)
{
R += 1;
B -= 1;
}
lblMarquee.ForeColor = Color.FromArgb(A, R, G, B);
}
解决方案
你的代码有很多问题,所以我想我会专注于这个。至于你的彩虹配色方案,即使你走在正确的轨道上,我也不确定。但是,假设您是这应该可以帮助您:
// never recreate the random class in your method
// always just create one
private static readonly Random _rand = new Random();
// your variables, make them byte as that's what we are dealing with
private static byte _r = 0;
private static byte _g = 0;
private static byte _b = 0;
private static byte _a = 0;
private static SomeMethod()
{
// make your life easier with some helper methods
void Inc(ref byte val)
=> val = (byte)(val>=255 ? 0: val++);
void Dec(ref byte val)
=> val = (byte)(val<=0 ? 255: val--);
// not sure why you want this
_a = (byte)_rand.Next(255);
_r += 1;
// I have no idea what your logic is here, but it looks neater
// and won't overflow, which is your problem
// however I seriously doubt this will give you a rainbow
if (_r > 250)
{
Inc(ref _g);
Dec(ref _r);
}
if (_g > 250)
{
Inc(ref _b);
Dec(ref _g);
}
if (_b > 250)
{
Inc(ref _r);
Dec(ref _b);
}
lblMarquee.ForeColor = Color.FromArgb(_a, _r, _g, _b);
}
推荐阅读
- ruby-on-rails - 如何处理使用相同控制器、动作和视图的不同类型?
- kdb - 在查询中除以计数并更新到新表
- salesforce - 如何通过 apex 代码从审批流程中获取步骤名称?
- javascript - 为什么const变量是这样定义的?
- angular - Angular Reactive Forms:在值更改之前检测用户输入
- android - 接收短信的广播服务
- class - 如何在联合继承中为查询的子实体返回正确的类?
- javascript - 解析授权标头时出现 NTLM 错误
- xamarin - 自定义字体不会通过自定义标签呈现器在 Xamarin.iOS 上加载
- java - 当用户在我的聊天中收到另一个用户的新消息时,如何创建通知?