Silverlight中验证码生成

   public class ValidationCode
    {
        Random r = new Random(DateTime.Now.Millisecond);

        /// <summary>
        /// 用于在生成验证码
        /// </summary>
        /// <param name="text">生成验证码的字符串</param>
        /// <param name="img">silverlight中的Imge控件</param>
        public void CreatImage(string text, Image img) 
        {
            int height =Convert.ToInt32(img.Height);
            int width = Convert.ToInt32(img.Width);
            Grid Gx = new Grid();

            //用于生成干扰线
            Canvas cv1 = new Canvas();
            for (int i = 0; i < 6; i++)
            {
                Polyline p = new Polyline();
                for (int ix = 0; ix < r.Next(3, 6); ix++)
                {
                    p.Points.Add(new Point(r.NextDouble() * width,
                        r.NextDouble() * height));
                }
                byte[] Buffer = new byte[3];
                r.NextBytes(Buffer);
                SolidColorBrush SC = new SolidColorBrush(Color.FromArgb(255,
                    Buffer[0], Buffer[1], Buffer[2]));
                p.Stroke = SC;
                p.StrokeThickness = 0.5;
                cv1.Children.Add(p);
            }
            Gx.Children.Add(cv1);

            //用于生成数字
            Canvas cv2 = new Canvas();
            int y = 0;
            int lw = 6;
            double w = (width - lw) / text.Length;
            int h = (int)height;
            foreach (char x in text)
            {
                byte[] Buffer = new byte[3];
                r.NextBytes(Buffer);  //用随机数填充字节数组的元素
                SolidColorBrush SC = new SolidColorBrush(Color.FromArgb(255,
                    Buffer[0], Buffer[1], Buffer[2]));
                TextBlock t = new TextBlock();
                t.TextAlignment = TextAlignment.Center;
                t.FontSize = r.Next(h - 3, h); //返回一个指定范围内的数  设定字体大小<像素高度-3>
                t.Foreground = SC;    //设置前景色
                t.Text = x.ToString();
                t.Projection = new PlaneProjection()  //对象的透视转换(类似三维效果)
                {
                    RotationX = r.Next(-30, 30),
                    RotationY = r.Next(-30, 30),
                    RotationZ = r.Next(-10, 10)
                };
                cv2.Children.Add(t);
                Canvas.SetLeft(t, lw / 2 + y * w);
                Canvas.SetTop(t, 0);
                y++;
            }

            Gx.Children.Add(cv2);

            //基于内存管理图像的类
            WriteableBitmap W = new WriteableBitmap(Gx, new TransformGroup());
            W.Render(Gx, new TransformGroup());

            img.Source = W;
        }
}


 

转载于:https://www.cnblogs.com/gudicao/p/4126871.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值