关于Graphics也有了基本了解下面想说的的是学这个东东干什么呢,到底如何应用
目前常见应用
1、验证码(参照网上的)
2、打印排版(会提到关于条形码大小设置)
3、自定义控件

一、验证码

     class ValidateCode
{
#region 定义和初始化配置字段 //用户存取验证码字符串
public string validationCode = String.Empty; //生成的验证码字符串
public char[] chars = null; /// <summary>
/// 获取随机验证码
/// </summary>
public String ValidationCode
{
get { return validationCode; }
} /// <summary>
/// 验证码字符串的长度
/// </summary>
private Int32 validationCodeCount = ; /// <summary>
/// 获取和设置验证码字符串的长度
/// </summary>
public Int32 ValidationCodeCount
{
get { return validationCodeCount; }
set { validationCodeCount = value; }
} /// <summary>
/// 画板对象
/// </summary>
Graphics dc = null; //验证码的宽度,默认为130
private int bgWidth = ; /// <summary>
/// 验证码的宽度,默认为130
/// </summary>
public Int32 Width
{
get { return bgWidth; }
set { bgWidth = value; }
} //验证码的宽度,默认为130
private int bgHeight = ; /// <summary>
/// 验证码的高度,默认为40
/// </summary>
public Int32 Height
{
get { return bgHeight; }
set { bgHeight = value; }
} //字体大小 字体最小值
private int fontMinSize = ; /// <summary>
/// 验证码字体的最小值,默认为20,建议不小于15像素
/// </summary>
public Int32 FontMinSize
{
get { return fontMinSize; }
set { fontMinSize = value; }
}
//字体大小 字体最大值
private Int32 fontMaxSize = ; /// <summary>
/// 验证码字体的最大值,默认为25
/// </summary>
public Int32 FontMaxSize
{
get { return fontMaxSize; }
set { fontMaxSize = value; }
} //验证码字体的颜色
private Color[] fontColor = { }; /// <summary>
/// 验证码字体的颜色,默认为系统自动生成字体颜色
/// </summary>
public Color[] FontColor
{
get { return fontColor; }
set { fontColor = value; }
} private Color backColor = Color.FromArgb(, , ); /// <summary>
/// 验证码的背景色,默认为Color.FromArgb(243, 251, 254)
/// </summary>
public Color BackgroundColor
{
get { return backColor; }
set { backColor = value; }
} //贝塞尔曲线的条数,默认为3条
private Int32 bezierCount = ; /// <summary>
/// 贝塞尔曲线的条数,默认为3条
/// </summary>
public Int32 BezierCount
{
get { return bezierCount; }
set { bezierCount = value; }
} //直线条数,默认为3条
private Int32 lineCount = ; /// <summary>
/// 直线条数,默认为3条
/// </summary>
public Int32 LineCount
{
get { return lineCount; }
set { lineCount = value; }
} //随机字符串列表
private String charCollection = "2,3,4,5,6,7,8,9,a,s,d,f,g,h,z,c,v,b,n,m,k,q,w,e,r,t,y,u,p,A,S,D,F,G,H,Z,C,V,B,N,M,K,Q,W,E,R,T,Y,U,P"; //定义验证码字符及出现频次 ,避免出现0 o j i l 1 x; /// <summary>
/// 随机字符串列表,请使用英文状态下的逗号分隔
/// </summary>
public String CharCollection
{
get { return charCollection; }
set { charCollection = value; }
} //验证码字符串个数,默认为4个字符
private Int32 intCount = ; /// <summary>
/// 验证码字符串个数,默认为4个字符
/// </summary>
public Int32 IntCount
{
get { return intCount; }
set { intCount = value; }
} //是否添加噪点,默认添加,噪点颜色为系统随机生成。
private Boolean isPixel = true;
/// <summary>
/// 是否添加噪点,默认添加,噪点颜色为系统随机生成。
/// </summary>
public Boolean IsPixel
{
get { return isPixel; }
set { isPixel = value; }
} //是否添加随机噪点字符串,默认添加
private Boolean isRandString = true;
/// <summary>
/// 是否添加随机噪点字符串,默认添加
/// </summary>
public Boolean IsRandString
{
get { return isRandString; }
set { isRandString = value; }
} /// <summary>
/// 随机背景字符串的个数
/// </summary>
public Int32 RandomStringCount
{
get; set;
} //随机背景字符串的大小
private Int32 randomStringFontSize = ;
/// <summary>
/// 随机背景字符串的大小
/// </summary>
public Int32 RandomStringFontSize
{
get { return randomStringFontSize; }
set { randomStringFontSize = value; }
} /// <summary>
/// 是否对图片进行扭曲
/// </summary>
public Boolean IsTwist
{
get; set;
} /// <summary>
/// 边框样式
/// </summary>
public enum BorderStyle
{
/// <summary>
/// 无边框
/// </summary>
None,
/// <summary>
/// 矩形边框
/// </summary>
Rectangle,
/// <summary>
/// 圆角边框
/// </summary>
RoundRectangle
} /// <summary>
/// 验证码字符串随机转动的角度 默认40
/// </summary>
private Int32 rotationAngle = ;
/// <summary>
/// 验证码字符串随机转动的角度的最大值
/// </summary>
public Int32 RotationAngle
{
get { return rotationAngle; }
set { rotationAngle = value; }
} /// <summary>
/// 设置或获取边框样式
/// </summary>
public BorderStyle Border
{
get; set;
} /// <summary>
/// 对验证码图片进行高斯模糊的阀值,如果设置为0
/// </summary>
private Double gaussianDeviation = ; /// <summary>
/// 对验证码图片进行高斯模糊的阀值,如果设置为0,则不对图片进行高斯模糊,该设置可能会对图片处理的性能有较大影响
/// </summary>
public Double GaussianDeviation
{
get { return gaussianDeviation; }
set { gaussianDeviation = value; }
}
private Int32 brightnessValue = ;
/// <summary>
/// 对图片进行暗度和亮度的调整,如果该值为0,则不调整。该设置会对图片处理性能有较大影响
/// </summary>
public Int32 BrightnessValue
{
get { return brightnessValue; }
set { brightnessValue = value; }
} #endregion private Point[] strPoint = null; Random random = new Random(); /// <summary>
/// 构造函数,用于初始化常用变量
/// </summary>
public void DrawValidationCode()
{
//随机对象
//Random类所取到的系统时钟种子接近甚至完全一样
//解决方案:new Random(Guid.NewGuid().GetHashCode());
random = new Random(Guid.NewGuid().GetHashCode());
//坐标数组
strPoint = new Point[validationCodeCount + ];
if (gaussianDeviation < )
gaussianDeviation = ;
} /// <summary>
/// 生成验证码
/// 思路:多张图片合成
/// 1.验证码背景图片
/// 1.1.背景包含
/// 1.1.1.背景颜色
/// 1.1.2.噪点
/// 1.1.3.干扰文字
/// 1.1.4.干扰线条(直线、曲线)
/// 2.验证码字符
/// 3.验证码图片扭曲
/// 4.验证码图片模糊
/// 5.验证码图片亮度
/// 6.验证码图片保持在内存流中
/// </summary>
/// <param name="target">用于存储图片的一般字节序列</param>
public MemoryStream CreateImage(string code)
{
MemoryStream target = new MemoryStream();
// 定义图片对象大小,
Bitmap bit = new Bitmap(bgWidth + , bgHeight + );
// 定义 Graphics(画板)根据图片对象
dc = Graphics.FromImage(bit);
/*
SmoothingModeAntiAlias 指定消除锯齿的呈现。
SmoothingModeDefault 指定默认模式。
SmoothingModeHighQuality 指定高质量、低速度呈现。
SmoothingModeHighSpeed 指定高速度、低质量呈现。
SmoothingModeInvalid 指定一个无效模式。
SmoothingModeNone 指定不消除锯齿。
*/
dc.SmoothingMode = SmoothingMode.HighQuality;
//文本的呈现模式
dc.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
// 插补模式
dc.InterpolationMode = InterpolationMode.HighQualityBilinear;
//合成图像的呈现质量
dc.CompositingQuality = CompositingQuality.HighQuality;
try
{
//清空画板,指定背景色(白色)
dc.Clear(Color.White);
DrawValidationCode();
//DrawImageUnscaled 在指定的位置使用图像的原始物理大小绘制指定的图像
// 验证码背景
dc.DrawImageUnscaled(DrawBackground(), , );
// 验证码字符
dc.DrawImageUnscaled(DrawRandomString(code), , );
//对图片文字进行扭曲
bit = AdjustRippleEffect(bit, );
//对图片进行高斯模糊
if (gaussianDeviation > )
{
Gaussian gau = new Gaussian();
bit = gau.FilterProcessImage(gaussianDeviation, bit);
}
//进行暗度和亮度处理
if (brightnessValue != )
{
//对图片进行调暗处理
bit = AdjustBrightness(bit, brightnessValue);
}
bit.Save(target, ImageFormat.Jpeg);
//输出图片流
return target; }
finally
{
//brush.Dispose();
bit.Dispose();
dc.Dispose();
}
} #region 画验证码背景,例如,增加早点,添加曲线和直线等
/// <summary>
/// 画验证码背景,例如,增加早点,添加曲线和直线等
/// 1.1.背景包含
/// 1.1.1.背景颜色
/// 1.1.2.噪点
/// 1.1.3.干扰文字
/// 1.1.4.干扰线条(直线、曲线)
/// </summary>
/// <returns>Bitmap 对象</returns>
private Bitmap DrawBackground()
{
Bitmap bit = new Bitmap(bgWidth + , bgHeight + );
Graphics g = Graphics.FromImage(bit);
g.SmoothingMode = SmoothingMode.HighQuality;
g.Clear(Color.White);
Rectangle rectangle = new Rectangle(, , bgWidth, bgHeight);
Brush brush = new SolidBrush(backColor);
//填充矩形
g.FillRectangle(brush, rectangle);
//画噪点
if (isPixel)
{
g.DrawImageUnscaled(DrawRandomPixel(), , );
}
// 背景干扰字符
g.DrawImageUnscaled(DrawRandBgString(), , );
//画曲线
//g.DrawImageUnscaled(DrawRandomBezier(bezierCount), 0, 0);
//画直线
//g.DrawImageUnscaled(DrawRandomLine(lineCount), 0, 0);
if (Border == BorderStyle.Rectangle)
{
//绘制边框
g.DrawRectangle(new Pen(Color.FromArgb(, , )), , , bgWidth, bgHeight);
}
else if (Border == BorderStyle.RoundRectangle)
{
//画圆角
DrawRoundRectangle(g, rectangle, Color.FromArgb(, , ), , );
}
return bit;
}
#endregion #region 画随机噪点
/// <summary>
/// 画随机噪点
/// 在指定区域中随机设置像素点的颜色
/// </summary>
/// <param name="pixNum">噪点的百分比</param>
/// <returns></returns>
public Bitmap DrawRandomPixel(Int32 pixNum)
{
Bitmap b = new Bitmap(bgWidth, bgHeight);
//透明化
b.MakeTransparent();
Graphics graph = Graphics.FromImage(b);
graph.SmoothingMode = SmoothingMode.HighQuality;
graph.InterpolationMode = InterpolationMode.HighQualityBilinear;
//画噪点
for (int i = ; i < (bgHeight * bgWidth) / pixNum; i++)
{
int x = random.Next(b.Width);
int y = random.Next(b.Height);
//设置随机像素点的颜色
b.SetPixel(x, y, GetRandomDeepColor());
//下移坐标重新画点
if ((x + ) < b.Width && (y + ) < b.Height)
{
//画图片的前景噪音点
graph.DrawRectangle(new Pen(Color.Silver), random.Next(b.Width), random.Next(b.Height), , );
}
}
return b;
}
#endregion #region 画干扰背景文字
/// <summary>
/// 画背景干扰文字
/// </summary>
/// <returns></returns>
private Bitmap DrawRandBgString()
{
Bitmap b = new Bitmap(bgWidth, bgHeight);
String[] randStr = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
//设置透明
b.MakeTransparent();
Graphics g = Graphics.FromImage(b);
g.Clear(Color.Transparent);
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.TextRenderingHint = TextRenderingHint.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBilinear;
//设置字体显示格式
StringFormat format = new StringFormat(StringFormatFlags.NoClip);
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
FontFamily f = new FontFamily(GenericFontFamilies.Serif);
Font textFont = new Font(f, randomStringFontSize, FontStyle.Underline);
int randAngle = ; //随机转动角度
for (int i = ; i < RandomStringCount; i++)
{
Brush brush = new System.Drawing.SolidBrush(GetRandomLightColor());
Point pot = new Point(random.Next(, bgWidth - ), random.Next(, bgHeight - ));
//随机转动的度数
float angle = random.Next(-randAngle, randAngle);
//转动画布
g.RotateTransform(angle);
g.DrawString(randStr[random.Next(randStr.Length)], textFont, brush, pot, format);
//转回去,为下一个字符做准备
g.RotateTransform(-angle);
//释放资源
brush.Dispose();
}
textFont.Dispose();
format.Dispose();
f.Dispose();
return b;
}
#endregion #region 随机生成贝塞尔曲线
/// <summary>
/// 随机生成贝塞尔曲线
/// </summary>
/// <param name="bmp">一个图片的实例</param>
/// <param name="lineNum">线条数量</param>
/// <returns></returns>
public Bitmap DrawRandomBezier(Int32 lineNum)
{
Bitmap b = new Bitmap(bgWidth, bgHeight);
b.MakeTransparent();
Graphics g = Graphics.FromImage(b);
g.Clear(Color.Transparent);
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
GraphicsPath gPath1 = new GraphicsPath();
Int32 lineRandNum = random.Next(lineNum);
for (int i = ; i < (lineNum - lineRandNum); i++)
{
Pen p = new Pen(GetRandomDeepColor());
Point[] point = {
new Point(random.Next(, (b.Width / )), random.Next(, (b.Height))),
new Point(random.Next((b.Width / ) * , (b.Width / ) * ), random.Next(, (b.Height))),
new Point(random.Next((b.Width / ) * , (b.Width / ) * ), random.Next(, (b.Height))),
new Point(random.Next((b.Width / ) * , b.Width), random.Next(, (b.Height)))
};
gPath1.AddBeziers(point);
g.DrawPath(p, gPath1);
p.Dispose();
}
for (int i = ; i < lineRandNum; i++)
{
Pen p = new Pen(GetRandomDeepColor());
Point[] point = {
new Point(random.Next(, b.Width), random.Next(, b.Height)),
new Point(random.Next((b.Width / ) * , b.Width), random.Next(, b.Height)),
new Point(random.Next((b.Width / ) * , b.Width), random.Next(, b.Height)),
new Point(random.Next(, b.Width), random.Next(, b.Height))
};
gPath1.AddBeziers(point);
g.DrawPath(p, gPath1);
p.Dispose();
}
return b;
}
#endregion #region 画直线
/// <summary>
/// 画直线
/// </summary>
/// <param name="bmp">一个bmp实例</param>
/// <param name="lineNum">线条个数</param>
/// <returns></returns>
public Bitmap DrawRandomLine(Int32 lineNum)
{
if (lineNum < ) throw new ArgumentNullException("参数bmp为空!");
Bitmap b = new Bitmap(bgWidth, bgHeight);
b.MakeTransparent();
Graphics g = Graphics.FromImage(b);
g.Clear(Color.Transparent);
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
for (int i = ; i < lineNum; i++)
{
Pen p = new Pen(GetRandomDeepColor());
Point pt1 = new Point(random.Next(, (b.Width / ) * ), random.Next(b.Height));
Point pt2 = new Point(random.Next((b.Width / ) * , b.Width), random.Next(b.Height));
g.DrawLine(p, pt1, pt2);
p.Dispose();
}
return b;
}
#endregion #region 写入验证码的字符串
/// <summary>
/// 写入验证码的字符串
/// </summary>
private Bitmap DrawRandomString(string Code)
{
if (fontMaxSize >= (bgHeight / ) * )
throw new ArgumentException("字体最大值参数FontMaxSize与验证码高度相近,这会导致描绘验证码字符串时出错,请重新设置参数!");
Bitmap b = new Bitmap(bgWidth, bgHeight);
b.MakeTransparent();
Graphics g = Graphics.FromImage(b);
g.Clear(Color.Transparent);
g.PixelOffsetMode = PixelOffsetMode.Half;
g.SmoothingMode = SmoothingMode.HighQuality;
g.TextRenderingHint = TextRenderingHint.SingleBitPerPixelGridFit;
g.InterpolationMode = InterpolationMode.HighQualityBilinear;
chars = Code.ToCharArray(); //拆散字符串成单字符数组
validationCode = chars.ToString();
//设置字体显示格式
StringFormat format = new StringFormat(StringFormatFlags.NoClip);
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
FontFamily f = new FontFamily(GenericFontFamilies.Monospace);
Int32 charNum = chars.Length;
Point sPoint = new Point();
Int32 fontSize = ;
validationCodeCount = charNum;
for (int i = ; i < validationCodeCount; i++)
{
//定义字体
Font textFont = new Font(f, random.Next(fontMinSize, fontMaxSize), FontStyle.Bold);
//定义画刷,用于写字符串
//Brush brush = new SolidBrush(GetRandomDeepColor());
Int32 textFontSize = Convert.ToInt32(textFont.Size);
fontSize = textFontSize;
//Point point = new Point(random.Next((bgWidth / charNum) * i + 5, (bgWidth / charNum) * (i + 1)), random.Next(bgHeight / 5 + textFontSize / 2, bgHeight - textFontSize / 2));
// 字符位置坐标
Point point = new Point(random.Next((bgWidth / charNum) * i + , (bgWidth / charNum) * (i + ) - (textFontSize / )), random.Next(bgHeight / + textFontSize / , bgHeight - textFontSize / ));
//如果当前字符X坐标小于字体的二分之一大小
if (point.X < textFontSize / )
{
point.X = point.X + textFontSize / ;
}
//防止文字叠加
if (i > && (point.X - sPoint.X < (textFontSize / + textFontSize / )))
{
point.X = point.X + textFontSize;
}
//如果当前字符X坐标大于图片宽度,就减去字体的宽度
if (point.X > (bgWidth - textFontSize / ))
{
point.X = bgWidth - textFontSize / ;
}
sPoint = point;
float angle = random.Next(-rotationAngle, rotationAngle);//转动的度数
g.TranslateTransform(point.X, point.Y);
g.RotateTransform(angle); Rectangle myretang = new Rectangle(, , Convert.ToInt32(textFont.Size), Convert.ToInt32(textFont.Size));
Color c = GetRandomDeepColor();
//设置渐变画刷
LinearGradientBrush mybrush2 = new LinearGradientBrush(myretang, c, GetLightColor(c, ), random.Next());
g.DrawString(chars[i].ToString(), textFont, mybrush2, , , format); g.RotateTransform(-angle);//转回去
g.TranslateTransform(-point.X, -point.Y);//移动光标到指定位置,每个字符紧凑显示,避免被软件识别
strPoint[i] = point;
textFont.Dispose();
mybrush2.Dispose();
}
return b;
}
#endregion #region 增加或減少亮度
/// <summary>
/// 增加或減少亮度
/// </summary>
/// <param name="img">System.Drawing.Image Source </param>
/// <param name="valBrightness">0~255</param>
/// <returns></returns>
public System.Drawing.Bitmap AdjustBrightness(System.Drawing.Image img, int valBrightness)
{
// 讀入欲轉換的圖片並轉成為 Bitmap
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(img);
for (int y = ; y < bitmap.Height; y++)
{
for (int x = ; x < bitmap.Width; x++)
{
// 取得每一個 pixel
var pixel = bitmap.GetPixel(x, y);
// 判斷 如果處理過後 255 就設定為 255 如果小於則設定為 0
var pR = ((pixel.R + valBrightness > ) ? : pixel.R + valBrightness) < ? : ((pixel.R + valBrightness > ) ? : pixel.R + valBrightness);
var pG = ((pixel.G + valBrightness > ) ? : pixel.G + valBrightness) < ? : ((pixel.G + valBrightness > ) ? : pixel.G + valBrightness);
var pB = ((pixel.B + valBrightness > ) ? : pixel.B + valBrightness) < ? : ((pixel.B + valBrightness > ) ? : pixel.B + valBrightness);
// 將改過的 RGB 寫回
System.Drawing.Color newColor = System.Drawing.Color.FromArgb(pixel.A, pR, pG, pB);
bitmap.SetPixel(x, y, newColor);
}
}
// 回傳結果
return bitmap;
}
#endregion #region 水波纹效果
/// <summary>
/// 水波纹效果
/// </summary>
/// <param name="src"></param>
/// <param name="nWave">坡度</param>
/// www.it165.net
/// <returns></returns>
public Bitmap AdjustRippleEffect(Bitmap src, short nWave)
{
int nWidth = src.Width;
int nHeight = src.Height;
// 透过公式进行水波纹的採样
PointF[,] fp = new PointF[nWidth, nHeight];
Point[,] pt = new Point[nWidth, nHeight];
Point mid = new Point();
mid.X = nWidth / ;
mid.Y = nHeight / ;
double newX, newY;
double xo, yo;
//先取样将水波纹座标跟RGB取出
for (int x = ; x < nWidth; ++x)
for (int y = ; y < nHeight; ++y)
{
xo = ((double)nWave * Math.Sin(2.0 * 3.1415 * (float)y / 128.0));
yo = ((double)nWave * Math.Cos(2.0 * 3.1415 * (float)x / 128.0));
newX = (x + xo);
newY = (y + yo);
if (newX > && newX < nWidth)
{
fp[x, y].X = (float)newX;
pt[x, y].X = (int)newX;
}
else
{
fp[x, y].X = (float)0.0;
pt[x, y].X = ;
}
if (newY > && newY < nHeight)
{
fp[x, y].Y = (float)newY;
pt[x, y].Y = (int)newY;
}
else
{
fp[x, y].Y = (float)0.0;
pt[x, y].Y = ;
}
}
//进行合成
Bitmap bSrc = (Bitmap)src.Clone();
// 依照 Format24bppRgb 每三个表示一 Pixel 0: 蓝 1: 绿 2: 红
BitmapData bitmapData = src.LockBits(new Rectangle(, , src.Width, src.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
BitmapData bmSrc = bSrc.LockBits(new Rectangle(, , bSrc.Width, bSrc.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
int scanline = bitmapData.Stride;
IntPtr Scan0 = bitmapData.Scan0;
IntPtr SrcScan0 = bmSrc.Scan0;
//指针在c#中是不提倡使用的,有关指针的操作被认为是不安全的(unsafe)。因此运行这段代码之前,先要改一个地方,否则编译不过无法运行。
//修改方法:找到你的项目,在项目图标上点右键,选项目属性(Properties),Build标签页里把Allow unsafe code勾选上
unsafe
{
//指针
byte* p = (byte*)(void*)Scan0;
byte* pSrc = (byte*)(void*)SrcScan0;
int nOffset = bitmapData.Stride - src.Width * ;
int xOffset, yOffset;
for (int y = ; y < nHeight; ++y)
{
for (int x = ; x < nWidth; ++x)
{
xOffset = pt[x, y].X;
yOffset = pt[x, y].Y;
if (yOffset >= && yOffset < nHeight && xOffset >= && xOffset < nWidth)
{
p[] = pSrc[(yOffset * scanline) + (xOffset * )];
p[] = pSrc[(yOffset * scanline) + (xOffset * ) + ];
p[] = pSrc[(yOffset * scanline) + (xOffset * ) + ];
}
p += ;
}
p += nOffset;
}
}
src.UnlockBits(bitmapData);
bSrc.UnlockBits(bmSrc);
return src;
}
#endregion #region 生成随机字符串
/// <summary>
/// 生成随机字符串
/// </summary>
/// <returns></returns>
public string GetRandomString(Int32 textLength)
{
string[] randomArray = charCollection.Split(','); //将字符串生成数组
int arrayLength = randomArray.Length;
string randomString = "";
for (int i = ; i < textLength; i++)
{
randomString += randomArray[random.Next(, arrayLength)];
}
return randomString; //长度是textLength +1
}
#endregion #region 随机生成颜色值
/// <summary>
/// 生成随机深颜色
/// </summary>
/// <returns></returns>
public Color GetRandomDeepColor()
{
int nRed, nGreen, nBlue;
// nBlue,nRed nGreen 相差大一点 nGreen 小一些
//int high = 255;
int redLow = ;
int greenLow = ;
int blueLow = ;
nRed = random.Next(redLow);
nGreen = random.Next(greenLow);
nBlue = random.Next(blueLow);
Color color = Color.FromArgb(nRed, nGreen, nBlue);
return color;
}
/// <summary>
/// 生成随机浅颜色
/// </summary>
/// <returns>randomColor</returns>
public Color GetRandomLightColor()
{
int nRed, nGreen, nBlue;
//越大颜色越浅
int low = ; //色彩的下限
int high = ; //色彩的上限
nRed = random.Next(high) % (high - low) + low;
nGreen = random.Next(high) % (high - low) + low;
nBlue = random.Next(high) % (high - low) + low;
Color color = Color.FromArgb(nRed, nGreen, nBlue);
return color;
}
/// <summary>
/// 获取与当前颜色值相加后的颜色
/// </summary>
/// <param name="c"></param>
/// <returns></returns>
public Color GetLightColor(Color c, Int32 value)
{
int nRed = c.R, nGreen = c.G, nBlue = c.B;
//越大颜色越浅
if (nRed + value < && nRed + value > )
{
nRed = c.R + ;
}
if (nGreen + value < && nGreen + value > )
{
nGreen = c.G + ;
}
if (nBlue + value < && nBlue + value > )
{
nBlue = c.B + ;
}
Color color = Color.FromArgb(nRed, nGreen, nBlue);
return color;
}
#endregion #region 绘制圆角矩形
/// <summary>
/// C# GDI+ 绘制圆角矩形
/// </summary>
/// <param name="g">Graphics 对象</param>
/// <param name="rectangle">Rectangle 对象,圆角矩形区域</param>
/// <param name="borderColor">边框颜色</param>
/// <param name="borderWidth">边框宽度</param>
/// <param name="r">圆角半径</param>
private static void DrawRoundRectangle(Graphics g, Rectangle rectangle, Color borderColor, float borderWidth, int r)
{
// 如要使边缘平滑,请取消下行的注释
g.SmoothingMode = SmoothingMode.HighQuality;
Pen p = new Pen(borderColor, borderWidth);
// 调用 getRoundRectangle 得到圆角矩形的路径,然后再进行绘制
g.DrawPath(p, getRoundRectangle(rectangle, r));
}
#endregion #region 根据普通矩形得到圆角矩形的路径
/// <summary>
/// 根据普通矩形得到圆角矩形的路径
/// </summary>
/// <param name="rectangle">原始矩形</param>
/// <param name="r">半径</param>
/// <returns>图形路径</returns>
private static GraphicsPath getRoundRectangle(Rectangle rectangle, int r)
{
int l = * r;
// 把圆角矩形分成八段直线、弧的组合,依次加到路径中
GraphicsPath gp = new GraphicsPath();
gp.AddLine(new Point(rectangle.X + r, rectangle.Y), new Point(rectangle.Right - r, rectangle.Y));
gp.AddArc(new Rectangle(rectangle.Right - l, rectangle.Y, l, l), 270F, 90F);
gp.AddLine(new Point(rectangle.Right, rectangle.Y + r), new Point(rectangle.Right, rectangle.Bottom - r));
gp.AddArc(new Rectangle(rectangle.Right - l, rectangle.Bottom - l, l, l), 0F, 90F);
gp.AddLine(new Point(rectangle.Right - r, rectangle.Bottom), new Point(rectangle.X + r, rectangle.Bottom));
gp.AddArc(new Rectangle(rectangle.X, rectangle.Bottom - l, l, l), 90F, 90F);
gp.AddLine(new Point(rectangle.X, rectangle.Bottom - r), new Point(rectangle.X, rectangle.Y + r));
gp.AddArc(new Rectangle(rectangle.X, rectangle.Y, l, l), 180F, 90F);
return gp;
}
#endregion
}

调用

         private void frmValidateCode_Load(object sender, EventArgs e)
{
ValidateCode vCode = new ValidateCode();
string code = vCode.GetRandomString();
MemoryStream stream = vCode.CreateImage(code);
pictureBox1.Image = new Bitmap(stream);
}

效果

戏说 .NET GDI+系列学习教程(三、Graphics类的应用_验证码)-LMLPHP

05-28 11:20