有時為了滿足現實的需要,我們想產生隨機的較深的顏色,比如:彩色二維碼,為了讓手機、二維碼識別裝置可以正確識別,必須使用較深的顏色。
如所示:
那麼,如何?呢?
以下為源碼:
//C# Code:
using System;
using System.Drawing;
namespace Lgms.Net.QRCode.Codec.Util
{
public class ColorUtil
{
public static System.Drawing.Color GetRandomColor()
{
Random randomNum_1 = new Random(Guid.NewGuid().GetHashCode());
System.Threading.Thread.Sleep(randomNum_1.Next(1));
int int_Red = randomNum_1.Next(255);
Random randomNum_2 = new Random((int)DateTime.Now.Ticks);
int int_Green = randomNum_2.Next(255);
Random randomNum_3 = new Random(Guid.NewGuid().GetHashCode());
int int_Blue = randomNum_3.Next(255);
int_Blue = (int_Red + int_Green > 380) ? int_Red + int_Green - 380 : int_Blue;
int_Blue = (int_Blue > 255) ? 255 : int_Blue;
return GetDarkerColor(System.Drawing.Color.FromArgb(int_Red, int_Green, int_Blue));
}
//擷取加深顏色
public static Color GetDarkerColor(Color color)
{
const int max = 255;
int increase = new Random(Guid.NewGuid().GetHashCode()).Next(30, 255); //還可以根據需要調整此處的值
int r = Math.Abs(Math.Min(color.R - increase, max));
int g = Math.Abs(Math.Min(color.G - increase, max));
int b = Math.Abs(Math.Min(color.B - increase, max));
return Color.FromArgb(r, g, b);
}
}
希望對有需要的朋友有用。