Reset() public method

public Reset ( ) : void
return void
Example #1
0
        public override void DrawEffectImage(Bitmap current, Bitmap next, EffectingPanel effecingPanel)
        {
            int step = 1;
            Graphics bg;
            Bitmap doubleBufferingBitmap;
            SolidBrush solidBrush;
            Rectangle rectangle;
            Matrix matrix = null;

            try
            {
                doubleBufferingBitmap = new Bitmap(current);        // ダブルバッファリング用画面
                bg = Graphics.FromImage(doubleBufferingBitmap);     // ダブルバッファリング用画面描画用Graphics

                solidBrush = new SolidBrush(System.Drawing.Color.Black);
                rectangle = new Rectangle(0, 0, current.Width, current.Height);
                matrix = new Matrix();

                step = doubleBufferingBitmap.Width / 50;
                if (step < 1)
                {
                    step = 1;
                }

                ResetInterval();

                for (int x = 0; x < doubleBufferingBitmap.Width; x += step)
                {
                    bg.ResetTransform();                        // リセット座標変換
                    bg.FillRectangle(solidBrush, rectangle);

                    // current画像
                    matrix.Reset();
                    matrix.Translate(x, 0, MatrixOrder.Append);    // 原点移動
                    bg.Transform = matrix;                         // 座標設定
                    bg.DrawImage(current, 0, 0);

                    // next画像
                    matrix.Reset();
                    matrix.Translate(x - doubleBufferingBitmap.Width, 0, MatrixOrder.Append);
                    bg.Transform = matrix;
                    bg.DrawImage(next, 0, 0);

                    effecingPanel.pictureBox.Image = doubleBufferingBitmap;
                    effecingPanel.pictureBox.Refresh();

                    DoEventAtIntervals();
                }

                matrix.Dispose();
                bg.Dispose();
                doubleBufferingBitmap.Dispose();

                effecingPanel.pictureBox.Image = next;
            }
            catch (SystemException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Example #2
0
        public static byte[] Generate()
        {
            string captchaString = random.Next(1000, 9999).ToString();
            HttpContext.Current.Session["captcha"] = captchaString;

            Bitmap image = new Bitmap(width, height);
            Graphics graphics = Graphics.FromImage(image);
            graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
            Matrix matrix = new Matrix();

            for (int i = 0; i < captchaLength; i++)
            {
                matrix.Reset();
                int x = (width / captchaLength) * i;
                int y = height / 2;
                matrix.RotateAt(random.Next(-40, 40), new PointF(x, y));
                graphics.Transform = matrix;
                graphics.DrawString(captchaString[i].ToString(),
                    new Font(FontFamily.GenericSerif, random.Next(25, 40)),
                    new SolidBrush(Color.FromArgb(random.Next(100), random.Next(100), random.Next(100))),
                    x, random.Next(5, 10));
            }

            MemoryStream ms = new MemoryStream();
            image.Save(ms, ImageFormat.Png);

            return ms.GetBuffer();
        }
Example #3
0
        internal static float ConvertSweepAngle(float sweepAngle, float startAngle, SpatialTransform transform, CoordinateSystem targetSystem)
        {
            PointF x = new PointF(100, 0);

            PointF[] startVector = new PointF[] { x };
            Matrix   rotation    = new Matrix();

            rotation.Rotate(startAngle);
            rotation.TransformVectors(startVector);

            PointF[] sweepVector = (PointF[])startVector.Clone();
            rotation.Reset();
            rotation.Rotate(sweepAngle);
            rotation.TransformVectors(sweepVector);
            rotation.Dispose();

            SizeF startVectorTransformed, sweepVectorTransformed;

            if (targetSystem == Graphics.CoordinateSystem.Destination)
            {
                startVectorTransformed = transform.ConvertToDestination(new SizeF(startVector[0]));
                sweepVectorTransformed = transform.ConvertToDestination(new SizeF(sweepVector[0]));
            }
            else
            {
                startVectorTransformed = transform.ConvertToSource(new SizeF(startVector[0]));
                sweepVectorTransformed = transform.ConvertToSource(new SizeF(sweepVector[0]));
            }

            // simply return the angle between the start and sweep angle, in the target system.
            return((int)Math.Round(Vector.SubtendedAngle(sweepVectorTransformed.ToPointF(), PointF.Empty, startVectorTransformed.ToPointF())));
        }
Example #4
0
        public OutlinedStringSurface(
            String str, Font font, Brush brush, Pen outlinePen,
            StringFormat stringFormat)
        {
            Contract.Requires(str != null);
            Contract.Requires(font != null);
            Contract.Requires(brush != null);
            Contract.Requires(outlinePen != null);

            _brush = brush;
            _outlinePen = outlinePen;

            // グラフィックスパスの生成
            _path = new GraphicsPath();
            _path.AddString(
                str, font.FontFamily, (int)font.Style, font.Size,
                new Point(0, 0), stringFormat);
            // サイズを取得する
            var rect = _path.GetBounds();
            Size = rect.Size.ToSize();
            // 描画時にマージンがなくなるように平行移動
            var matrix = new Matrix(1, 0, 0, 1, -rect.Left, -rect.Top);
            _path.Transform(matrix);
            // 描画位置を(0, 0)で記憶
            matrix.Reset();
            _matrix = matrix;
        }
    public void DrawImage()
    {
        //Creates an output Bitmap
        Bitmap   oOutputBitmap = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb);
        Graphics oGraphics     = Graphics.FromImage(oOutputBitmap);

        oGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;

        //Create a Drawing area
        RectangleF oRectangleF = new RectangleF(0, 0, iWidth, iHeight);
        Brush      oBrush      = default(Brush);

        //Draw background (Lighter colors RGB 100 to 255)
        oBrush = new HatchBrush(aHatchStyles[oRandom.Next
                                                 (aHatchStyles.Length - 1)], Color.FromArgb((oRandom.Next(100, 255)),
                                                                                            (oRandom.Next(100, 255)), (oRandom.Next(100, 255))), Color.White);
        oGraphics.FillRectangle(oBrush, oRectangleF);

        System.Drawing.Drawing2D.Matrix oMatrix = new System.Drawing.Drawing2D.Matrix();
        int i = 0;

        for (i = 0; i <= sCaptchaText.Length - 1; i++)
        {
            oMatrix.Reset();
            int iChars = sCaptchaText.Length;
            int x      = iWidth / (iChars + 1) * i;
            int y      = iHeight / 2;

            //Rotate text Random
            oMatrix.RotateAt(oRandom.Next(-20, 20), new PointF(x, y));
            oGraphics.Transform = oMatrix;

            //Draw the letters with Random Font Type, Size and Color
            oGraphics.DrawString
            (
                //Text
                sCaptchaText.Substring(i, 1),
                //Random Font Name and Style
                new Font(aFontNames[oRandom.Next(aFontNames.Length - 1)],
                         aFontEmSizes[oRandom.Next(aFontEmSizes.Length - 1)],
                         aFontStyles[oRandom.Next(aFontStyles.Length - 1)]),
                //Random Color (Darker colors RGB 0 to 100)
                new SolidBrush(Color.FromArgb(oRandom.Next(0, 100),
                                              oRandom.Next(0, 100), oRandom.Next(0, 100))),
                x,
                oRandom.Next(0, 15)
            );
            oGraphics.ResetTransform();
        }

        MemoryStream oMemoryStream = new MemoryStream();

        oOutputBitmap.Save(oMemoryStream, System.Drawing.Imaging.ImageFormat.Png);
        byte[] oBytes = oMemoryStream.GetBuffer();
        captchaImage = "data:image/png;base64," + Convert.ToBase64String(oBytes, 0, oBytes.Length);
        oOutputBitmap.Dispose();
        oMemoryStream.Close();
    }
Example #6
0
 /// <summary>
 /// Will Draw a rectangle in this view
 /// </summary>
 /// <param name="rectangle">The size and scale of the rectangle</param>
 /// <param name="edgeColor">The Color of the rectangle edge</param>
 /// <param name="edgeWidth">The width of the rectangels outer edge</param>
 /// <param name="tranformation">The Affine Transformation that will be applied to this line. Note this member is not required and can be null</param>
 /// <returns>If True the line was drawn successfully, If False the draw was abourted due to an error</returns>
 public bool paintRectangle(System.Drawing.RectangleF rectangle, System.Drawing.Color fillColor, System.Drawing.Color edgeColor, float edgeWidth, Matrix tranformation)
 {
     //Can only Draw one Rectangle at a time, sorry
     if (rectangle != null && edgeColor != null && edgeWidth >= 0)
     {
         if (aquirePaintLock())
         {
             if (currentGraphicsObject != null)
             {
                 //Transform
                 publicMatrix.Reset();
                 if (tranformation != null)
                 {
                     publicMatrix.Multiply(tranformation, MatrixOrder.Append);
                 }
                 publicMatrix.Multiply(cameraTransform, MatrixOrder.Append);
                 currentGraphicsObject.Transform = publicMatrix;
                 //Fill Brush
                 if (fillColor != null && fillColor.A > 0)
                 {
                     publicBrush.Color = fillColor;
                     currentGraphicsObject.FillRectangle(publicBrush, rectangle);
                 }
                 //Edge Pen
                 if (edgeColor != null && edgeColor.A > 0)
                 {
                     publicPen.Color = edgeColor;
                     publicPen.Width = edgeWidth;
                     currentGraphicsObject.DrawRectangle(publicPen, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height);
                 }
                 releasePaintLock();
                 return(true);
             }
             releasePaintLock();
         }
     }
     return(false);
 }
Example #7
0
        public override void DrawEffectImage(Bitmap current, Bitmap next, EffectingPanel effecingPanel)
        {
            Bitmap doubleBufferingBitmap = null;    // ダブルバッファリング用画面
            Graphics bg = null;                     // ダブルバッファリング用画面描画用Graphics

            SolidBrush solidBrush = null;
            Rectangle rectangle;
            Matrix matrix = null;

            try
            {
                int deltaDegree = 10;

                doubleBufferingBitmap = new Bitmap(current);
                bg = Graphics.FromImage(doubleBufferingBitmap);

                solidBrush = new SolidBrush(System.Drawing.Color.Black);
                rectangle = new Rectangle(0, 0, current.Width, current.Height);
                matrix = new Matrix();

                ResetInterval();
                for (int angle = 0; angle <= 360; angle += deltaDegree)
                {
                    bg.ResetTransform();                             // リセット座標変換
                    bg.FillRectangle(solidBrush, rectangle);

                    matrix.Reset();
                    matrix.Translate(doubleBufferingBitmap.Width / 2, doubleBufferingBitmap.Height / 2, MatrixOrder.Append);   // 原点移動
                    matrix.Rotate((float)angle);
                    bg.Transform = matrix;                           // 座標設定

                    bg.DrawImage(current, -doubleBufferingBitmap.Width / 2, -doubleBufferingBitmap.Height / 2);  // 画像の中心が(0, 0)になるように描画
                    effecingPanel.pictureBox.Image = doubleBufferingBitmap;
                    effecingPanel.pictureBox.Refresh();

                    Thread.Sleep(20);
                    DoEventAtIntervals();
                }

                matrix.Dispose();
                bg.Dispose();
                doubleBufferingBitmap.Dispose();
            }
            catch(SystemException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Example #8
0
        /// <summary>
        /// If the any of the would to cameraSpace variables are updated will recalculate the cameraTransform
        /// </summary>
        private void updateCameraTransform()
        {
            if (cameraTransformChanged)
            {
                //Reseting camera Transform
                cameraTransform.Reset();
                //Translation to origin
                cameraTransform.Translate(-worldCenter.X, -worldCenter.Y, MatrixOrder.Append);;
                //Scale
                if (worldScale.X != 0 && worldScale.Y != 0 && (worldScale.X != 1 || worldScale.Y != 1))
                {
                    cameraTransform.Scale(worldScale.X, worldScale.Y, MatrixOrder.Append);
                }
                //Shear
                if ((worldShear.X != 1 || worldShear.Y != 1) && (worldShear.X != 0 || worldShear.Y != 0))
                {
                    cameraTransform.Shear(worldShear.X, worldShear.Y, MatrixOrder.Append);
                }
                //Rotation
                if (worldRotation != 0)
                {
                    cameraTransform.Rotate(worldRotation, MatrixOrder.Append);
                }
                //Moving Center to Centr
                if (drawBuffers != null)
                {
                    cameraTransform.Translate(drawBuffers[0].Width / 2, drawBuffers[0].Height / 2, MatrixOrder.Append);
                }
                else
                {
                    cameraTransform.Translate(base.Width / 2, base.Height / 2, MatrixOrder.Append);
                }
                cameraTransformChanged = false;

                //invers Transform
                setInverseCameraTransform();
                if (attachedMouse != null)
                {
                    attachedMouse.setTransform(inverseCameraTransform);
                }
            }
        }
Example #9
0
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            using (Graphics g = e.Graphics)
            {
                try
                {
                    // рисуем изображение без трасформаций 
                    g.DrawImage(new Bitmap(@"Boxs.bmp"), 0, 0, 100, 100);
                }
                catch { }
                // Создаем матрицу
                Matrix X = new Matrix();
                // Установка трансформаций
                X.RotateAt(45,new Point(150,150));
                X.Translate(100, 100);
                g.Transform = X;
                try
                {
                    // рисуем изображение
                    g.DrawImage(new Bitmap(@"Rings.bmp"), 0, 0, 100, 100);
                }
                catch { }

                // Сброс трансформаций
                X.Reset();
                // Установка трансформаций
                X.RotateAt(25, new Point(50, 150));
                X.Translate(150, 10);
                X.Shear(0.5f, 0.3f);
                g.Transform = X;
                try
                {
                    // рисуем изображение
                    g.DrawImage(new Bitmap(@"Cells.bmp"), 0, 0, 100, 100);
                }
                catch { }

            }

        }
Example #10
0
        protected override List<PointF> CreateShape(List<Point> tracePoints)
        {
            Point a = tracePoints[0];
            Point b = tracePoints[tracePoints.Count - 1];
            Point dir = new Point(b.X - a.X, b.Y - a.Y);
            float len = (float)Math.Sqrt(dir.X * dir.X + dir.Y * dir.Y);

            RectangleF rectF;

            if ((ModifierKeys & Keys.Shift) != 0)
            {
                PointF center = new PointF((float)(a.X + b.X) / 2.0f, (float)(a.Y + b.Y) / 2.0f);
                float radius = len / 2;
                rectF = Rectangle.Truncate(Utility.RectangleFromCenter(center, radius));
            }
            else
            {
                rectF = Utility.PointsToRectangle(a, b);
            }

            Rectangle rect = Utility.RoundRectangle(rectF);
            PdnGraphicsPath path = new PdnGraphicsPath();
            path.AddEllipse(rect);

            // Avoid asymmetrical circles where the left or right side of the ellipse has a pixel jutting out
            using (Matrix m = new Matrix())
            {
                m.Reset();
                m.Translate(-0.5f, -0.5f, MatrixOrder.Append);
                path.Transform(m);
            }

            path.Flatten(Utility.IdentityMatrix, 0.1f);

            PointF[] pointsF = path.PathPoints;
            path.Dispose();

            return new List<PointF>(pointsF);
        }
Example #11
0
        public void Draw(Surface dst, int tX, int tY)
        {
            if (this.disposed)
            {
                throw new ObjectDisposedException("MaskedSurface");
            }

            using (Matrix m = new Matrix())
            {
                m.Reset();
                m.Translate(tX, tY, MatrixOrder.Append);
                Draw(dst, m, ResamplingAlgorithm.Bilinear);
            }
        }
 public void ResetTransform()
 {
     gradientTransform.Reset();
     changed = true;
 }
Example #13
0
        private void RenderTo(Graphics g)
        {
            SvgDocument svgdoc = tlVectorControl1.SVGDocument;
            Matrix matrix1 = new Matrix();
            Matrix matrix2 = new Matrix();
            matrix1 = ((SVG)svgdoc.RootElement).GraphTransform.Matrix;
            matrix2.Multiply(matrix1);
            matrix1.Reset();
            matrix1.Multiply(g.Transform);
            g.ResetTransform();
            try {

                SVG svg1 = svgdoc.DocumentElement as SVG;
                svgdoc.BeginPrint = true;
                SmoothingMode mode1 = svgdoc.SmoothingMode;
                svgdoc.SmoothingMode = g.SmoothingMode;
                svg1.Draw(g, svgdoc.ControlTime);
                svgdoc.SmoothingMode = mode1;
                svgdoc.BeginPrint = false;
            } finally {
                g.Transform = matrix1.Clone();
                matrix1.Reset();
                matrix1.Multiply(matrix2);
            }
        }
Example #14
0
 private void RenderTo(Graphics g)
 {
     Matrix matrix1=new Matrix();
     Matrix matrix2=new Matrix();
     matrix1=((SVG)this.vectorcontrol.SVGDocument.RootElement).GraphTransform.Matrix;
     matrix2.Multiply(matrix1);
     matrix1.Reset();
     matrix1.Multiply(g.Transform);
     g.ResetTransform();
     g.TranslateTransform(10,10);
     try
     {
         this.vectorcontrol.RenderTo(g);
     }
     finally
     {
         g.Transform=matrix1.Clone();
         matrix1.Reset();
         matrix1.Multiply(matrix2);
     }
 }
Example #15
0
		protected override void CreateHandles()
		{
			if (Container == null) return;
			SetHandles(new Handles());

			//Get the default graphics path and scale it
			IRender render = RenderFromContainer();
			GraphicsPath defaultPath = (GraphicsPath) Component.Instance.DefaultHandlePath.Clone();
			Matrix matrix = new Matrix();
			matrix.Scale(render.ZoomFactor,render.ZoomFactor);
			defaultPath.Transform(matrix);
			RectangleF pathRectangle = defaultPath.GetBounds();
			RectangleF halfRectangle = new RectangleF(0,0,pathRectangle.Width /2, pathRectangle.Height /2);

			//Loop through each point and add an offset handle
			GraphicsPath path;

			foreach (PointF point in Points)
			{
				path = (GraphicsPath) defaultPath.Clone();
				matrix.Reset();
				matrix.Translate(point.X - Rectangle.X - halfRectangle.Width,point.Y - Rectangle.Y - halfRectangle.Height);
				path.Transform(matrix);
				Handles.Add(new Handle(path, HandleType.Origin));
			}

			Handles[0].CanDock = true;
			Handles[Handles.Count-1].CanDock = true;
		}
Example #16
0
        public ActionResult Show(string key)
        {
            var randomText = GenerateRandomText(6);

            Session["DogrulamaKodu"] = randomText;
            var hash = ComputeMd5Hash(randomText + GetSalt());
            //Session["CaptchaHash"] = hash;

            var       rnd              = new Random();
            var       fonts            = new[] { "Oswald", "sans-serif" };
            float     orientationAngle = rnd.Next(0, 359);
            const int height           = 80;
            const int width            = 190;
            var       index0           = rnd.Next(0, fonts.Length);
            var       familyName       = fonts[index0];

            /*Eski yapıya ekleme*/
            int[]    aFontEmSizes = new int[] { 18, 22, 26, 30, 34 };
            string[] aFontNames   = new string[]
            {
                "Comic Sans MS",
                "Arial",
                "Times New Roman",
                "Georgia",
                "Verdana",
                "Geneva"
            };
            FontStyle[] aFontStyles = new FontStyle[]
            {
                FontStyle.Bold,
                FontStyle.Italic,
                FontStyle.Regular,
                FontStyle.Strikeout,
                FontStyle.Underline
            };

            HatchStyle[] aHatchStyles = new HatchStyle[]
            {
                HatchStyle.BackwardDiagonal, HatchStyle.Cross,
                HatchStyle.DashedDownwardDiagonal, HatchStyle.DashedHorizontal,
                HatchStyle.DashedUpwardDiagonal, HatchStyle.DashedVertical,
                HatchStyle.DiagonalBrick, HatchStyle.DiagonalCross,
                HatchStyle.Divot, HatchStyle.DottedDiamond, HatchStyle.DottedGrid,
                HatchStyle.ForwardDiagonal, HatchStyle.Horizontal,
                HatchStyle.HorizontalBrick, HatchStyle.LargeCheckerBoard,
                HatchStyle.LargeConfetti, HatchStyle.LargeGrid,
                HatchStyle.LightDownwardDiagonal, HatchStyle.LightHorizontal,
                HatchStyle.LightUpwardDiagonal, HatchStyle.LightVertical,
                HatchStyle.Max, HatchStyle.Min, HatchStyle.NarrowHorizontal,
                HatchStyle.NarrowVertical, HatchStyle.OutlinedDiamond,
                HatchStyle.Plaid, HatchStyle.Shingle, HatchStyle.SmallCheckerBoard,
                HatchStyle.SmallConfetti, HatchStyle.SmallGrid,
                HatchStyle.SolidDiamond, HatchStyle.Sphere, HatchStyle.Trellis,
                HatchStyle.Vertical, HatchStyle.Wave, HatchStyle.Weave,
                HatchStyle.WideDownwardDiagonal, HatchStyle.WideUpwardDiagonal, HatchStyle.ZigZag
            };

            using (var bmpOut = new Bitmap(width, height))
            {
                var g = Graphics.FromImage(bmpOut);

                var gradientBrush = new LinearGradientBrush(new Rectangle(0, 0, width, height),
                                                            Color.Transparent, Color.Transparent,
                                                            orientationAngle);
                g.FillRectangle(gradientBrush, 0, 0, width, height);
                DrawRandomLines(ref g, width, height);
                System.Drawing.Drawing2D.Matrix oMatrix = new System.Drawing.Drawing2D.Matrix();
                int i = 0;
                for (i = 0; i <= randomText.Length - 1; i++)
                {
                    oMatrix.Reset();
                    int iChars = randomText.Length;
                    int x      = width / (iChars + 1) * i;
                    int y      = height / 2;

                    //Rotate text Random
                    oMatrix.RotateAt(rnd.Next(-40, 40), new PointF(x, y));
                    g.Transform = oMatrix;

                    //Draw the letters with Random Font Type, Size and Color
                    g.DrawString
                    (
                        //Text
                        randomText.Substring(i, 1),
                        //Random Font Name and Style
                        new Font(aFontNames[rnd.Next(aFontNames.Length - 1)],
                                 aFontEmSizes[rnd.Next(aFontEmSizes.Length - 1)],
                                 aFontStyles[rnd.Next(aFontStyles.Length - 1)]),
                        //Random Color (Darker colors RGB 0 to 100)
                        new SolidBrush(Color.FromArgb(52, 158, 209)),
                        x,
                        rnd.Next(10, 40)
                    );
                    g.ResetTransform();
                }
                /*Ekleme Sonrası*/
                MemoryStream oMemoryStream = new MemoryStream();
                bmpOut.Save(oMemoryStream, System.Drawing.Imaging.ImageFormat.Png);
                byte[] oBytes   = oMemoryStream.GetBuffer();
                var    bmpBytes = oMemoryStream.GetBuffer();
                bmpOut.Dispose();
                oMemoryStream.Close();
                return(new FileContentResult(bmpBytes, "image/png"));
            }
        }
Example #17
0
        /// <summary>创建验证码图片</summary>
        /// <param name="verifyCodeImageInfo">验证码图片信息</param>
        public void CreateVerifyCodeImage(VerifyCodeImageInfo verifyCodeImageInfo)
        {
            int textLength = verifyCodeImageInfo.Text.Length;
            if(textLength == 0 || verifyCodeImageInfo.ImageWidth == 0 || verifyCodeImageInfo.ImageHeight == 0) return;

            using(Bitmap img = new Bitmap(verifyCodeImageInfo.ImageWidth, verifyCodeImageInfo.ImageHeight, PixelFormat.Format32bppArgb))
            {
                using(GraphicsPath p = new GraphicsPath())
                {
                    using(Graphics g = Graphics.FromImage(img))
                    {
                        g.SmoothingMode = SmoothingMode.AntiAlias;
                        g.Clear(verifyCodeImageInfo.BackgroundColor);

                        int charSize = (int)(Math.Min(verifyCodeImageInfo.ImageHeight, (int)(verifyCodeImageInfo.ImageWidth / textLength)) * 0.8);
                        PointF charPoint = new PointF();
                        int halfCharSize = (int)(charSize * 0.5f);
                        int paddingHeight = (int)(verifyCodeImageInfo.ImageHeight * 0.8) - charSize;

                        using(Matrix matrix = new Matrix())
                        {
                            using(Pen pen = new Pen(Color.Empty))
                            {
                                using(StringFormat format = new StringFormat())
                                {
                                    format.Alignment = StringAlignment.Near;
                                    format.LineAlignment = StringAlignment.Near;
                                    FontFamily f;
                                    for(int i = 0; i < textLength; i++)
                                    {
                                        charPoint.X = (float)(i * charSize + Utils.Rand((int)(charSize * 0.2f), (int)(charSize * 0.8f)));
                                        charPoint.Y = (float)Utils.Rand(2, paddingHeight);

                                        p.Reset();
                                        float fs = charSize * Utils.Rand(80, 120) * 0.01f;
                                        f = GetFontFamily(verifyCodeImageInfo.Fonts);
                                        p.AddString(verifyCodeImageInfo.Text[i].ToString(), f, 0, fs, new Point(0, 0), format);

                                        matrix.Reset();
                                        matrix.RotateAt((float)Utils.Rand(-60, 60), new PointF(charPoint.X + halfCharSize, charPoint.Y + halfCharSize));
                                        matrix.Translate(charPoint.X, charPoint.Y);
                                        p.Transform(matrix);

                                        pen.Color = GetTextColor(verifyCodeImageInfo.RandomTextColor, verifyCodeImageInfo.TextColor);
                                        pen.Width = Utils.Rand(1, 2);
                                        g.DrawPath(pen, p);
                                        g.DrawBezier(pen,
                                            Utils.Rand(verifyCodeImageInfo.ImageWidth),
                                            Utils.Rand(verifyCodeImageInfo.ImageHeight),
                                            Utils.Rand(verifyCodeImageInfo.ImageWidth),
                                            Utils.Rand(verifyCodeImageInfo.ImageHeight),
                                            Utils.Rand(verifyCodeImageInfo.ImageWidth),
                                            Utils.Rand(verifyCodeImageInfo.ImageHeight),
                                            Utils.Rand(verifyCodeImageInfo.ImageWidth),
                                            Utils.Rand(verifyCodeImageInfo.ImageHeight));
                                    }
                                }
                                pen.Color = GetTextColor(verifyCodeImageInfo.RandomTextColor, verifyCodeImageInfo.TextColor);
                                pen.Width = Utils.Rand(1, 2);
                                g.DrawBezier(pen,
                                    Utils.Rand(verifyCodeImageInfo.ImageWidth),
                                    0,
                                    Utils.Rand(verifyCodeImageInfo.ImageWidth),
                                    Utils.Rand(verifyCodeImageInfo.ImageHeight),
                                    Utils.Rand(verifyCodeImageInfo.ImageWidth),
                                    Utils.Rand(verifyCodeImageInfo.ImageHeight),
                                    Utils.Rand(verifyCodeImageInfo.ImageWidth),
                                    verifyCodeImageInfo.ImageHeight);
                                pen.Width = Utils.Rand(1, 2);
                                pen.Color = GetTextColor(verifyCodeImageInfo.RandomTextColor, verifyCodeImageInfo.TextColor);
                                g.DrawBezier(pen,
                                    0,
                                    Utils.Rand(verifyCodeImageInfo.ImageHeight),
                                    Utils.Rand(verifyCodeImageInfo.ImageWidth),
                                    Utils.Rand(verifyCodeImageInfo.ImageHeight),
                                    Utils.Rand(verifyCodeImageInfo.ImageWidth),
                                    Utils.Rand(verifyCodeImageInfo.ImageHeight),
                                    verifyCodeImageInfo.ImageWidth,
                                    Utils.Rand(verifyCodeImageInfo.ImageHeight));
                            }
                        }
                    }
                }
                verifyCodeImageInfo.ImageData = img.Clone() as Image;
            }
        }
Example #18
0
        /// <summary>
        /// Create a mirror of the image in x and/or y
        /// </summary>
        /// <param name="source"></param>
        /// <param name="luminance"></param>
        public static void MirrorImage(Image source, bool xMirror, bool yMirror)
        {
            // get transform values

            float xTransform = (xMirror == true ? -1.0f : 1.0f);

            float yTransform = (yMirror == true ? -1.0f : 1.0f);

            // generate matrix to flip the image based on current settings

            Matrix m = new Matrix();

            m.Reset();

            // we are going to draw the image at the origin so transform so that the origin is at the center of image

            m.Translate((float)source.Width / 2.0f * xTransform, (float)source.Height / 2.0f * yTransform, MatrixOrder.Prepend);

            // scale which flips the image

            m.Scale(xTransform, yTransform, MatrixOrder.Append);

            // get a graphics object for the original image

            Graphics g = Graphics.FromImage(source);

            // set compositing mode to copy over

            g.CompositingMode = CompositingMode.SourceCopy;

            // turn off aliasing etc

            g.InterpolationMode = InterpolationMode.NearestNeighbor;

            g.SmoothingMode = SmoothingMode.None;

            // set transform into graphics

            g.Transform = m;

            // draw image at origin ( which is now translated to center of window )

            g.DrawImage(source, -((float)source.Width / 2.0f), -((float)source.Height / 2.0f));

            // dispose locals

            g.Dispose();
        }
Example #19
0
 public void PaintAxisGridAndTicks(Graphics g, Axis a, bool marks, TVec3 o, TVec3 o_, TVec3 L)
 {
     a.MinorGridEnabled = false;
     a.MinorTicksEnabled = false;
     int nTicks = (int)(L.NormInf / 10.0);
     if (nTicks < 3)
         nTicks = 3;
     if (nTicks > 10)
         nTicks = 10;
     TAxisCalc taxisCalc = new TAxisCalc(o, o + L, a.Min, a.Max, nTicks);
     TVec3 tvec3_1 = o_ - o;
     TVec3 tvec3_2 = TVec3.O;
     TVec3 tvec3_3 = -0.04 * tvec3_1;
     if (o_.y > o.y)
     {
         tvec3_2 = tvec3_1;
         tvec3_3 = -tvec3_3;
     }
     TVec3 tvec3_4 = tvec3_2 + 1.04 * tvec3_3;
     if (a.GridEnabled)
     {
         Pen pen = new Pen(a.GridColor, a.GridWidth);
         for (int i = 0; i < taxisCalc.nTicks; ++i)
             g.DrawLine(pen, (Point)taxisCalc.TickPos(i), (Point)(taxisCalc.TickPos(i) + tvec3_1));
     }
     if (a.Position == EAxisPosition.Right && tvec3_3.x <= 0.0)
         marks = false;
     if (!marks)
         return;
     int num1 = a.Position == EAxisPosition.Bottom ? 0 : 1;
     int num2 = a.Position == EAxisPosition.Bottom ? taxisCalc.nTicks - 1 : taxisCalc.nTicks;
     float num3 = 0.0f;
     if (a.MajorTicksEnabled)
     {
         Pen pen = new Pen(a.GridColor, a.GridWidth);
         for (int i = num1; i < num2; ++i)
             g.DrawLine(pen, (Point)(taxisCalc.TickPos(i) + tvec3_2), (Point)(taxisCalc.TickPos(i) + tvec3_2 + tvec3_3));
     }
     if (a.LabelEnabled)
     {
         Font labelFont = a.LabelFont;
         float height = labelFont.GetHeight(g);
         SolidBrush solidBrush = new SolidBrush(a.LabelColor);
         StringFormat format = new StringFormat();
         float num4;
         if (a.Position == EAxisPosition.Bottom)
         {
             format.FormatFlags = StringFormatFlags.DirectionVertical;
             num4 = (float)Math.Abs(taxisCalc.TickPos(1).x - taxisCalc.TickPos(0).x);
         }
         else
         {
             tvec3_4.y -= 0.5 * (double)a.LabelFont.GetHeight();
             num4 = (float)Math.Abs(taxisCalc.TickPos(1).y - taxisCalc.TickPos(0).y);
         }
         if (tvec3_3.x < 0.0)
             tvec3_4.x -= (double)a.LabelFont.GetHeight();
         if ((double)num4 > 0.0)
         {
             int num5 = (int)((double)height / (double)num4 + 1.0);
             if (num1 + num5 < num2)
             {
                 int i = num1;
                 while (i < num2)
                 {
                     if (i + num5 >= num2)
                         i = num2 - 1;
                     TVec3 tvec3_5 = taxisCalc.TickPos(i) + tvec3_4;
                     string str = taxisCalc.TickVal(i).ToString();
                     g.DrawString(str, labelFont, (Brush)solidBrush, (PointF)tvec3_5, format);
                     SizeF sizeF = g.MeasureString(str, labelFont);
                     if ((double)sizeF.Width > (double)num3)
                         num3 = sizeF.Width;
                     i += num5;
                 }
             }
             else if (num2 > 0)
             {
                 int i = num2 - 1;
                 TVec3 tvec3_5 = taxisCalc.TickPos(i) + tvec3_4;
                 string str = taxisCalc.TickVal(i).ToString();
                 g.DrawString(str, labelFont, (Brush)solidBrush, (PointF)tvec3_5, format);
                 num3 = g.MeasureString(str, labelFont).Width;
             }
         }
     }
     if (!a.TitleEnabled)
         return;
     SizeF sizeF1 = g.MeasureString(a.Title, a.TitleFont);
     PointF point1;
     PointF point2;
     float angle;
     if (a.Position == EAxisPosition.Bottom)
     {
         if (tvec3_3.x < 0.0)
         {
             point1 = taxisCalc.TickPos(0).x > taxisCalc.TickPos(1).x ? (PointF)(taxisCalc.TickPos(taxisCalc.nTicks - 1) + tvec3_4) : (PointF)(taxisCalc.TickPos(0) + tvec3_4);
             point1.Y += num3;
             point2 = point1;
             angle = (float)(Math.Atan2(Math.Abs(L.y), Math.Abs(L.x)) * 180.0 / Math.PI);
         }
         else
         {
             point1 = taxisCalc.TickPos(0).x > taxisCalc.TickPos(1).x ? (PointF)(taxisCalc.TickPos(0) + tvec3_4) : (PointF)(taxisCalc.TickPos(taxisCalc.nTicks - 1) + tvec3_4);
             point1.X += a.LabelFont.GetHeight(g);
             point1.Y += num3;
             point2 = point1;
             point2.X -= sizeF1.Width;
             angle = (float)(-Math.Atan2(Math.Abs(L.y), Math.Abs(L.x)) * 180.0 / Math.PI);
         }
     }
     else
     {
         point1 = taxisCalc.TickPos(0).z > taxisCalc.TickPos(1).z ? (PointF)(taxisCalc.TickPos(0) + tvec3_4) : (PointF)(taxisCalc.TickPos(taxisCalc.nTicks - 1) + tvec3_4);
         point1.X += num3;
         point2 = point1;
         point2.X -= sizeF1.Width;
         angle = -90f;
     }
     Matrix matrix = new Matrix();
     matrix.RotateAt(angle, point1, MatrixOrder.Append);
     g.Transform = matrix;
     g.DrawString(a.Title, a.LabelFont, (Brush)new SolidBrush(a.LabelColor), point2);
     matrix.Reset();
     g.Transform = matrix;
 }
Example #20
0
        public static PdnGraphicsPath FromRegions(PdnRegion lhs, CombineMode combineMode, PdnRegion rhs)
        {
            Rectangle lhsBounds = lhs.GetBoundsInt();
            Rectangle rhsBounds = rhs.GetBoundsInt();
            int left = Math.Min(lhsBounds.Left, rhsBounds.Left);
            int top = Math.Min(lhsBounds.Top, rhsBounds.Top);
            int right = Math.Max(lhsBounds.Right, rhsBounds.Right);
            int bottom = Math.Max(lhsBounds.Bottom, rhsBounds.Bottom);
            Rectangle bounds = Rectangle.FromLTRB(left, top, right, bottom);
            BitVector2D stencil = new BitVector2D(bounds.Width, bounds.Height);
            Rectangle[] lhsScans = lhs.GetRegionScansReadOnlyInt();
            Rectangle[] rhsScans = rhs.GetRegionScansReadOnlyInt();

            switch (combineMode)
            {
                case CombineMode.Complement:
                case CombineMode.Intersect:
                case CombineMode.Replace:
                    throw new ArgumentException("combineMode can't be Complement, Intersect, or Replace");

                default:
                    break;
            }

            for (int i = 0; i < lhsScans.Length; ++i)
            {
                Rectangle rect = lhsScans[i];
                rect.X -= bounds.X;
                rect.Y -= bounds.Y;

                stencil.SetUnchecked(rect, true);
            }

            for (int i = 0; i < rhsScans.Length; ++i)
            {
                Rectangle rect = rhsScans[i];
                rect.X -= bounds.X;
                rect.Y -= bounds.Y;

                switch (combineMode)
                {
                    case CombineMode.Xor:
                        stencil.InvertUnchecked(rect);
                        break;

                    case CombineMode.Union:
                        stencil.SetUnchecked(rect, true);
                        break;
                    
                    case CombineMode.Exclude:
                        stencil.SetUnchecked(rect, false);
                        break;
                }
            }

            PdnGraphicsPath path = PathFromStencil(stencil, new Rectangle(0, 0, stencil.Width, stencil.Height));

            using (Matrix matrix = new Matrix())
            {
                matrix.Reset();
                matrix.Translate(bounds.X, bounds.Y);
                path.Transform(matrix);
            }

            return path;
        }
Example #21
0
 public Matrix GetInterimTransformCopy()
 {
     lock (this.syncRoot)
     {
         if (this.data.interimTransform == null)
         {
             Matrix m = new Matrix();
             m.Reset();
             return m;
         }
         else
         {
             return this.data.interimTransform.Clone();
         }
     }
 }
Example #22
0
        public VerifyImageInfo GenerateImage(string code, int width, int height, Color bgcolor, int textcolor)
        {
            VerifyImageInfo verifyimage = new VerifyImageInfo();
            verifyimage.ImageFormat = ImageFormat.Jpeg;
            verifyimage.ContentType = "image/pjpeg";

            Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);

            Graphics g = Graphics.FromImage(bitmap);
            Rectangle rect = new Rectangle(0, 0, width, height);
            g.SmoothingMode = SmoothingMode.AntiAlias;

            g.Clear(bgcolor);

            int fixedNumber = textcolor == 2 ? 60 : 0;

            SolidBrush drawBrush = new SolidBrush(Color.FromArgb(Next(100), Next(100), Next(100)));
            for (int x = 0; x < 3; x++)
            {
                Pen linePen = new Pen(Color.FromArgb(Next(150) + fixedNumber, Next(150) + fixedNumber, Next(150) + fixedNumber),1);
                g.DrawLine(linePen, new PointF(0.0F + Next(20), 0.0F + Next(height)), new PointF(0.0F + Next(width), 0.0F + Next(height)));
            }

            Matrix m = new Matrix();
            for (int x = 0; x < code.Length; x++)
            {
                m.Reset();
                m.RotateAt(Next(30) - 15, new PointF(Convert.ToInt64(width * (0.10 * x)), Convert.ToInt64(height * 0.5)));
                g.Transform = m;
                drawBrush.Color = Color.FromArgb(Next(150) + fixedNumber + 20, Next(150) + fixedNumber + 20, Next(150) + fixedNumber + 20);
                PointF drawPoint = new PointF(0.0F + Next(4) + x * 20, 3.0F + Next(3));
                g.DrawString(Next(1) == 1 ? code[x].ToString() : code[x].ToString().ToUpper(), fonts[Next(fonts.Length - 1)], drawBrush, drawPoint);
                g.ResetTransform();
            }

            double distort = Next(5, 10) * (Next(10) == 1 ? 1 : -1);

            using (Bitmap copy = (Bitmap)bitmap.Clone())
            {
                for (int y = 0; y < height; y++)
                {
                    for (int x = 0; x < width; x++)
                    {
                        int newX = (int)(x + (distort * Math.Sin(Math.PI * y / 84.5)));
                        int newY = (int)(y + (distort * Math.Cos(Math.PI * x / 54.5)));
                        if (newX < 0 || newX >= width)
                            newX = 0;
                        if (newY < 0 || newY >= height)
                            newY = 0;
                        bitmap.SetPixel(x, y, copy.GetPixel(newX, newY));
                    }
                }
            }

            //g.DrawRectangle(new Pen(Color.Silver), 0, 0, bitmap.Width - 1, bitmap.Height - 1);

            drawBrush.Dispose();
            g.Dispose();

            verifyimage.Image = bitmap;

            return verifyimage;
        }
		/// <summary>
		/// Called by the base <see cref="SpatialTransform"/> to post-multiply an operation to the overall transformation matrix.
		/// </summary>
		protected override void CalculatePostTransform(Matrix cumulativeTransform)
		{
			cumulativeTransform.Reset();
			cumulativeTransform.Translate(this.TranslationX, this.TranslationY);
		}
Example #24
0
        public void ProcessRequest(HttpContext context)
        {
            int captchaStr = new Random().Next(6, 12);
            context.Session["captcha"] = GenerateRandomString(captchaStr);
            const int iHeight = 70;
            const int iWidth = 250;
            var oRandom = new Random();
            int[] aFontEmSizes = { 15, 20, 25, 30 };
            string[] aFontNames = { "Comic Sans MS", "Arial", "Times New Roman", "Georgia", "Verdana", "Geneva" };

            FontStyle[] aFontStyles =
            {
                FontStyle.Bold,
                FontStyle.Italic,
                FontStyle.Regular,
                FontStyle.Strikeout,
                FontStyle.Underline
            };

            HatchStyle[] aHatchStyles =
            {
                HatchStyle.BackwardDiagonal, HatchStyle.Cross, HatchStyle.DashedDownwardDiagonal, HatchStyle.DashedHorizontal,
                HatchStyle.DashedUpwardDiagonal, HatchStyle.DashedVertical, HatchStyle.DiagonalBrick, HatchStyle.DiagonalCross,
                HatchStyle.Divot, HatchStyle.DottedDiamond, HatchStyle.DottedGrid, HatchStyle.ForwardDiagonal, HatchStyle.Horizontal,
                HatchStyle.HorizontalBrick, HatchStyle.LargeCheckerBoard, HatchStyle.LargeConfetti, HatchStyle.LargeGrid,
                HatchStyle.LightDownwardDiagonal, HatchStyle.LightHorizontal, HatchStyle.LightUpwardDiagonal, HatchStyle.LightVertical,
                HatchStyle.Max, HatchStyle.Min, HatchStyle.NarrowHorizontal, HatchStyle.NarrowVertical, HatchStyle.OutlinedDiamond,
                HatchStyle.Plaid, HatchStyle.Shingle, HatchStyle.SmallCheckerBoard, HatchStyle.SmallConfetti, HatchStyle.SmallGrid,
                HatchStyle.SolidDiamond, HatchStyle.Sphere, HatchStyle.Trellis, HatchStyle.Vertical, HatchStyle.Wave, HatchStyle.Weave,
                HatchStyle.WideDownwardDiagonal, HatchStyle.WideUpwardDiagonal, HatchStyle.ZigZag
            };

            //Get Captcha in Session
            string sCaptchaText = context.Session["captcha"].ToString();

            //Creates an output Bitmap
            var oOutputBitmap = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb);
            var oGraphics = Graphics.FromImage(oOutputBitmap);
            oGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;

            //Create a Drawing area
            var oRectangleF = new RectangleF(0, 0, iWidth, iHeight);

            //Draw background (Lighter colors RGB 100 to 255)
            Brush oBrush = new HatchBrush(aHatchStyles[oRandom.Next(aHatchStyles.Length - 1)], Color.Gainsboro, Color.White);//HatchBrush(aHatchStyles[oRandom.Next(aHatchStyles.Length - 1)], Color.FromArgb((oRandom.Next(100, 255)), (oRandom.Next(100, 255)), (oRandom.Next(100, 255))), Color.White);
            oGraphics.FillRectangle(oBrush, oRectangleF);

            var oMatrix = new Matrix();
            int i;
            for (i = 0; i <= sCaptchaText.Length - 1; i++)
            {
                oMatrix.Reset();
                int iChars = sCaptchaText.Length;
                int x = iWidth / (iChars + 1) * i;
                const int y = iHeight / 2;

                //Rotate text Random
                oMatrix.RotateAt(oRandom.Next(-40, 40), new PointF(x, y));
                oGraphics.Transform = oMatrix;

                //Draw the letters with Randon Font Type, Size and Color
                oGraphics.DrawString
                (
                    //Text
                sCaptchaText.Substring(i, 1),
                    //Random Font Name and Style
                new Font(aFontNames[oRandom.Next(aFontNames.Length - 1)], aFontEmSizes[oRandom.Next(aFontEmSizes.Length - 1)], aFontStyles[oRandom.Next(aFontStyles.Length - 1)]),
                    //Random Color (Darker colors RGB 0 to 100)
                new SolidBrush(Color.FromArgb(oRandom.Next(0, 100), oRandom.Next(0, 100), oRandom.Next(0, 100))),
                x,
                oRandom.Next(10, 40)
                );
                oGraphics.ResetTransform();
            }

            context.Response.ContentType = "image/JPEG";
            //render image
            oOutputBitmap.Save(context.Response.OutputStream, ImageFormat.Jpeg);
            //dispose everything, we do not need them any more.
            oOutputBitmap.Dispose();
            oGraphics.Dispose();
            Console.WriteLine();
            context.Response.End();
        }
Example #25
0
		public MatrixComponents GetMatrixComponents()
		{
			System.Drawing.Drawing2D.Matrix srcMatrix = new System.Drawing.Drawing2D.Matrix(
				this.ScaleX,
				this.Rotate0,
				this.Rotate1,
				this.ScaleY,
				this.TranslateX,
				this.TranslateY);
			System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix(1, 0, 0, 1, 0, 0); // identity
			// an 'identity' box
			PointF[] modPts = new PointF[]{	new PointF(0,0),
											new PointF(1,0),
											new PointF(1,1),
											new PointF(0,1) };

			float sx, sy, rot, shear, tx, ty;

			srcMatrix.TransformPoints(modPts);

			// translation
			tx = srcMatrix.OffsetX;
			ty = srcMatrix.OffsetY;
			m.Translate(-tx, -ty);
			m.TransformPoints(modPts);
			m.Reset();

			// rotation
			rot = (float)Math.Atan2(modPts[1].Y, modPts[1].X); // x axis
			rot = (float)(rot / Math.PI * 180);
			if (rot == -0) rot = 0;
			if (rot == -180) rot = 180;
			m.Rotate(-1 * rot);
			m.TransformPoints(modPts);
			m.Reset();

            // scale
            //sx = Dist(modPts[0], modPts[3]); // bug it seems..?
            sx = Dist(modPts[0], modPts[1]);
			sy = Dist(modPts[0], new PointF(0, modPts[3].Y));
			if (modPts[0].Y > modPts[3].Y)
			{
				sy *= -1;
			}
			m.Scale(1 / sx, 1 / sy);
			m.TransformPoints(modPts);
			m.Reset();

			// skew
			// ySkew is impossible at this rotation
			shear = modPts[3].X / Dist(modPts[0], modPts[1]);
			// rounding
			shear = Math.Abs(shear) < 0.001 ? 0 : shear;
			m.Shear(-shear, 0);
			m.TransformPoints(modPts);

			m.Dispose();
			srcMatrix.Dispose();

			return new MatrixComponents(sx, sy, rot, shear, tx, ty);
		}
        //public void ProcessRequest(HttpContext context)
        //{
        //    context.Response.ContentType = "text/plain";
        //    context.Response.Write("Hello World");
        //}
        public void ProcessRequest(HttpContext context)
        {
            const int iHeight = 90;
            const int iWidth = 210;
            var oRandom = new Random();

            var aBackgroundNoiseColor = new int[] { 150, 150, 150 };
            var aTextColor = new int[] { 0, 0, 0 };
            var aFontEmSizes = new[] { 15, 20, 25, 30, 35 };

            var aFontNames = new[]
                                      {
                                          "Comic Sans MS",
                                          "Arial",
                                          "Times New Roman",
                                          "Georgia",
                                          "Verdana",
                                          "Geneva"
                                      };
            var aFontStyles = new[]
                                          {
                                              FontStyle.Bold,
                                              FontStyle.Italic,
                                              FontStyle.Regular,
                                              FontStyle.Strikeout,
                                              FontStyle.Underline
                                          };
            var aHatchStyles = new[]
                                            {
                                                HatchStyle.BackwardDiagonal, HatchStyle.Cross,
                                                HatchStyle.DashedDownwardDiagonal, HatchStyle.DashedHorizontal,
                                                HatchStyle.DashedUpwardDiagonal, HatchStyle.DashedVertical,
                                                HatchStyle.DiagonalBrick, HatchStyle.DiagonalCross,
                                                HatchStyle.Divot, HatchStyle.DottedDiamond, HatchStyle.DottedGrid,
                                                HatchStyle.ForwardDiagonal, HatchStyle.Horizontal,
                                                HatchStyle.HorizontalBrick, HatchStyle.LargeCheckerBoard,
                                                HatchStyle.LargeConfetti, HatchStyle.LargeGrid,
                                                HatchStyle.LightDownwardDiagonal, HatchStyle.LightHorizontal,
                                                HatchStyle.LightUpwardDiagonal, HatchStyle.LightVertical,
                                                HatchStyle.Max, HatchStyle.Min, HatchStyle.NarrowHorizontal,
                                                HatchStyle.NarrowVertical, HatchStyle.OutlinedDiamond,
                                                HatchStyle.Plaid, HatchStyle.Shingle, HatchStyle.SmallCheckerBoard,
                                                HatchStyle.SmallConfetti, HatchStyle.SmallGrid,
                                                HatchStyle.SolidDiamond, HatchStyle.Sphere, HatchStyle.Trellis,
                                                HatchStyle.Vertical, HatchStyle.Wave, HatchStyle.Weave,
                                                HatchStyle.WideDownwardDiagonal, HatchStyle.WideUpwardDiagonal,
                                                HatchStyle.ZigZag
                                            };

            //Get Captcha in Session
            string sCaptchaText = context.Session["Captcha2"].ToString();

            //Creates an output Bitmap
            var oOutputBitmap = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb);
            var oGraphics = Graphics.FromImage(oOutputBitmap);
            oGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;

            //Create a Drawing area
            var oRectangleF = new RectangleF(0, 0, iWidth, iHeight);

            //Draw background (Lighter colors RGB 100 to 255)
            Brush oBrush = new HatchBrush(aHatchStyles[oRandom.Next
                                                           (aHatchStyles.Length - 1)], Color.FromArgb((oRandom.Next(100, 255)),
                                                                                                      (oRandom.Next(100, 255)), (oRandom.Next(100, 255))), Color.White);
            oGraphics.FillRectangle(oBrush, oRectangleF);

            var oMatrix = new Matrix();
            int i;
            for (i = 0; i <= sCaptchaText.Length - 1; i++)
            {
                oMatrix.Reset();
                var iChars = sCaptchaText.Length;
                var x = iWidth / (iChars + 1) * i;
                var y = iHeight / 2;

                //Rotate text Random
                oMatrix.RotateAt(oRandom.Next(-40, 40), new PointF(x, y));
                oGraphics.Transform = oMatrix;

                //Draw the letters with Random Font Type, Size and Color
                oGraphics.DrawString
                (
                    //Text
                sCaptchaText.Substring(i, 1),
                    //Random Font Name and Style
                new Font(aFontNames[oRandom.Next(aFontNames.Length - 1)],
                   aFontEmSizes[oRandom.Next(aFontEmSizes.Length - 1)],
                   aFontStyles[oRandom.Next(aFontStyles.Length - 1)]),
                    //Random Color (Darker colors RGB 0 to 100)
                new SolidBrush(Color.FromArgb(oRandom.Next(0, 100),
                   oRandom.Next(0, 100), oRandom.Next(0, 100))),
                x,
                oRandom.Next(10, 40)
                );
                oGraphics.ResetTransform();
            }

            var oMemoryStream = new MemoryStream();
            oOutputBitmap.Save(oMemoryStream, ImageFormat.Png);
            var oBytes = oMemoryStream.GetBuffer();

            oOutputBitmap.Dispose();
            oMemoryStream.Close();

            context.Response.BinaryWrite(oBytes);
            context.Response.End();
        }
Example #27
0
        public void Repaint()
        {
            float R2pS = 2.0f*vr_R+vr_s;

            float xo = 0.5f*visual.Width;
            float yo = 0.5f*visual.Height-3.0f*Maths.Sqrt3_4*R2pS;
            GraphicsPath gpRing = new GraphicsPath();
            gpRing.AddEllipse(-vr_R+xo,-vr_R+yo,2.0f*vr_R,2.0f*vr_R);
            gpRing.AddEllipse(-vr_r+xo,-vr_r+yo,2.0f*vr_r,2.0f*vr_r);
            GraphicsPath gpBall = new GraphicsPath();
            gpBall.AddEllipse(-vr_rb+xo,-vr_rb+yo,2.0f*vr_rb,2.0f*vr_rb);
            float dx;
            int k;
            Matrix M = new Matrix();
            Matrix My = new Matrix();
            My.Translate(0.0f,Maths.Sqrt3_4*R2pS);
            ZertzPiece zp;
            Brush[] bs = new Brush[]{EgyptInformation.Brushes.EgyptNocturne,EgyptInformation.Brushes.EgyptPaintYellow,EgyptInformation.Brushes.EgyptPaintWhite};
            using(Graphics g = Graphics.FromImage(this.visual)) {
                g.Clear(Color.Transparent);
                for(int j = 0x00; j < 0x07; j++) {
                    for(int i = 0x00; i < 0x07; i++) {
                        zp = this.pieces[i,j];
                        k = zp.State;
                        if(k > 0x00) {
                            dx = R2pS*((i-0x03)+0.5f*(j-0x03));
                            M.Reset();
                            M.Translate(dx,0.0f);
                            gpRing.Transform(M);
                            g.FillPath(EgyptInformation.Brushes.EgyptPaintRed,gpRing);
                            g.DrawPath(Pens.Black,gpRing);
                            if(zp.ContainsBall) {
                                gpBall.Transform(M);
                                g.FillPath(bs[(int) zp.BallType],gpBall);
                                g.DrawPath(Pens.Black,gpBall);
                                M.Reset();
                                M.Translate(-dx,0.0f);
                                gpBall.Transform(M);
                                gpRing.Transform(M);
                            }
                            else {
                                M.Reset();
                                M.Translate(-dx,0.0f);
                                gpRing.Transform(M);
                            }
                        }
                    }
                    gpRing.Transform(My);
                    gpBall.Transform(My);
                }
            }
        }
Example #28
0
        private Matrix SetupTransform()
        {
            Point centerPosition = CalculateImageCenter();

            Matrix matrix = new Matrix();
            matrix.Reset();

            // Now translate the matrix into position for the scrollbars
            if (centerPosition.X != 0)
                matrix.Translate(centerPosition.X, 0);
            else
                matrix.Translate(this.AutoScrollPosition.X, 0);

            if (centerPosition.Y != 0)
                matrix.Translate(0, centerPosition.Y);
            else
                matrix.Translate(0, this.AutoScrollPosition.Y);

            matrix.Scale(this.zoom, this.zoom);

            return matrix;
        }
Example #29
0
        public static System.IO.MemoryStream GenerateCheckCode(out string checkCode)
        {
            checkCode = string.Empty;
            System.Drawing.Color color = System.Drawing.ColorTranslator.FromHtml("#1AE61A");
            char[] array = new char[]
            {
                '2',
                '3',
                '4',
                '5',
                '6',
                '8',
                '9',
                'A',
                'B',
                'C',
                'D',
                'E',
                'F',
                'G',
                'H',
                'J',
                'K',
                'L',
                'M',
                'N',
                'P',
                'R',
                'S',
                'T',
                'W',
                'X',
                'Y'
            };
            System.Random random = new System.Random();
            for (int i = 0; i < 4; i++)
            {
                checkCode += array[random.Next(array.Length)];
            }
            int width = 85;

            System.Drawing.Bitmap   bitmap   = new System.Drawing.Bitmap(width, 30);
            System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap);
            System.Random           random2  = new System.Random(System.DateTime.Now.Millisecond);
            System.Drawing.Brush    brush    = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(4683611));
            graphics.Clear(System.Drawing.ColorTranslator.FromHtml("#EBFDDF"));
            using (System.Drawing.StringFormat stringFormat = new System.Drawing.StringFormat())
            {
                stringFormat.Alignment     = System.Drawing.StringAlignment.Center;
                stringFormat.LineAlignment = System.Drawing.StringAlignment.Center;
                stringFormat.FormatFlags   = System.Drawing.StringFormatFlags.NoWrap;
                System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix();
                float num  = -25f;
                float num2 = 0f;
                graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                for (int i = 0; i < checkCode.Length; i++)
                {
                    int num3 = random2.Next(20, 24);
                    System.Drawing.Font  font  = ImageHelper.CreateFont(IOHelper.GetMapPath("/fonts/checkCode.ttf"), (float)num3, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 0);
                    System.Drawing.SizeF sizeF = graphics.MeasureString(checkCode[i].ToString(), font);
                    matrix.RotateAt((float)random2.Next(-15, 10), new System.Drawing.PointF(num + sizeF.Width / 2f, num2 + sizeF.Height / 2f));
                    graphics.Transform = matrix;
                    graphics.DrawString(checkCode[i].ToString(), font, System.Drawing.Brushes.Green, new System.Drawing.RectangleF(num, num2, (float)bitmap.Width, (float)bitmap.Height), stringFormat);
                    num  += sizeF.Width * 3f / 5f;
                    num2 += 0f;
                    graphics.RotateTransform(0f);
                    matrix.Reset();
                    font.Dispose();
                }
            }
            System.Drawing.Pen     pen          = new System.Drawing.Pen(System.Drawing.Color.Black, 0f);
            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
            System.IO.MemoryStream result;
            try
            {
                bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
                result = memoryStream;
            }
            finally
            {
                bitmap.Dispose();
                graphics.Dispose();
            }
            return(result);
        }
Example #30
0
        public void ProcessRequest(HttpContext context)
        {
            int    iHeight = 80;
            int    iWidth  = 190;
            Random oRandom = new Random();

            int[] aBackgroundNoiseColor = new int[] { 150, 150, 150 };
            int[] aTextColor            = new int[] { 0, 0, 0 };
            int[] aFontEmSizes          = new int[] { 15, 20, 25, 30, 35 };

            string[] aFontNames = new string[]
            {
                "Comic Sans MS",
                "Arial",
                "Times New Roman",
                "Georgia",
                "Verdana",
                "Geneva"
            };

            FontStyle[] aFontStyles = new FontStyle[]
            {
                FontStyle.Bold,
                FontStyle.Italic,
                FontStyle.Regular,
                FontStyle.Strikeout,
                FontStyle.Underline
            };
            HatchStyle[] aHatchStyles = new HatchStyle[]
            {
                HatchStyle.BackwardDiagonal, HatchStyle.Cross,
                HatchStyle.DashedDownwardDiagonal, HatchStyle.DashedHorizontal,
                HatchStyle.DashedUpwardDiagonal, HatchStyle.DashedVertical,
                HatchStyle.DiagonalBrick, HatchStyle.DiagonalCross,
                HatchStyle.Divot, HatchStyle.DottedDiamond, HatchStyle.DottedGrid,
                HatchStyle.ForwardDiagonal, HatchStyle.Horizontal,
                HatchStyle.HorizontalBrick, HatchStyle.LargeCheckerBoard,
                HatchStyle.LargeConfetti, HatchStyle.LargeGrid,
                HatchStyle.LightDownwardDiagonal, HatchStyle.LightHorizontal,
                HatchStyle.LightUpwardDiagonal, HatchStyle.LightVertical,
                HatchStyle.Max, HatchStyle.Min, HatchStyle.NarrowHorizontal,
                HatchStyle.NarrowVertical, HatchStyle.OutlinedDiamond,
                HatchStyle.Plaid, HatchStyle.Shingle, HatchStyle.SmallCheckerBoard,
                HatchStyle.SmallConfetti, HatchStyle.SmallGrid,
                HatchStyle.SolidDiamond, HatchStyle.Sphere, HatchStyle.Trellis,
                HatchStyle.Vertical, HatchStyle.Wave, HatchStyle.Weave,
                HatchStyle.WideDownwardDiagonal, HatchStyle.WideUpwardDiagonal, HatchStyle.ZigZag
            };

            //Get Captcha in Session
            string sCaptchaText = context.Session["Captcha"].ToString();

            //Creates an output Bitmap
            Bitmap   oOutputBitmap = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb);
            Graphics oGraphics     = Graphics.FromImage(oOutputBitmap);

            oGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;

            //Create a Drawing area
            RectangleF oRectangleF = new RectangleF(0, 0, iWidth, iHeight);
            Brush      oBrush      = default(Brush);

            //Draw background (Lighter colors RGB 100 to 255)
            oBrush = new HatchBrush(aHatchStyles[oRandom.Next
                                                     (aHatchStyles.Length - 1)], Color.FromArgb((oRandom.Next(100, 255)),
                                                                                                (oRandom.Next(100, 255)), (oRandom.Next(100, 255))), Color.White);
            oGraphics.FillRectangle(oBrush, oRectangleF);

            System.Drawing.Drawing2D.Matrix oMatrix = new System.Drawing.Drawing2D.Matrix();
            int i = 0;

            for (i = 0; i <= sCaptchaText.Length - 1; i++)
            {
                oMatrix.Reset();
                int iChars = sCaptchaText.Length;

                int x = iWidth / (iChars + 1) * i;
                int y = iHeight / 2;

                //Rotate text Random
                oMatrix.RotateAt(oRandom.Next(-40, 40), new PointF(x, y));
                oGraphics.Transform = oMatrix;


                //Draw the letters with Random Font Type, Size and Color
                oGraphics.DrawString
                (
                    //Text
                    sCaptchaText.Substring(i, 1),
                    //Random Font Name and Style
                    new Font(aFontNames[oRandom.Next(aFontNames.Length - 1)],
                             aFontEmSizes[oRandom.Next(aFontEmSizes.Length - 1)],
                             aFontStyles[oRandom.Next(aFontStyles.Length - 1)]),
                    //Random Color (Darker colors RGB 0 to 100)
                    new SolidBrush(Color.FromArgb(oRandom.Next(0, 100),
                                                  oRandom.Next(0, 100), oRandom.Next(0, 100))),
                    x,
                    oRandom.Next(10, 40)
                );
                oGraphics.ResetTransform();
            }

            MemoryStream oMemoryStream = new MemoryStream();

            oOutputBitmap.Save(oMemoryStream, System.Drawing.Imaging.ImageFormat.Png);
            byte[] oBytes = oMemoryStream.GetBuffer();


            oOutputBitmap.Dispose();
            oMemoryStream.Close();

            context.Response.BinaryWrite(oBytes);
            context.Response.End();
        }
        public Bitmap GenerateImage(int codeLength, int width, int height, Color bgcolor, int textcolor)
        {
            this._randomCode = CreateRandomCode(codeLength);
            string code = this._randomCode;
            Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);

            Graphics g = Graphics.FromImage(bitmap);
            Rectangle rect = new Rectangle(0, 0, width, height);
            g.SmoothingMode = SmoothingMode.AntiAlias;

            g.Clear(bgcolor);

            int fixedNumber = textcolor == 2 ? 60 : 0;

            SolidBrush drawBrush = new SolidBrush(Color.FromArgb(RandomUtils.GetRandomNumber(100), RandomUtils.GetRandomNumber(100), RandomUtils.GetRandomNumber(100)));
            for (int x = 0; x < 3; x++)
            {
                Pen linePen = new Pen(Color.FromArgb(RandomUtils.GetRandomNumber(150) + fixedNumber, RandomUtils.GetRandomNumber(150) + fixedNumber, RandomUtils.GetRandomNumber(150) + fixedNumber), 1);
                g.DrawLine(linePen, new PointF(0.0F + RandomUtils.GetRandomNumber(20), 0.0F + RandomUtils.GetRandomNumber(height)), new PointF(0.0F + RandomUtils.GetRandomNumber(width), 0.0F + RandomUtils.GetRandomNumber(height)));
            }

            Matrix m = new Matrix();
            for (int x = 0; x < code.Length; x++)
            {
                m.Reset();
                m.RotateAt(RandomUtils.GetRandomNumber(30) - 15, new PointF(Convert.ToInt64(width * (0.10 * x)), Convert.ToInt64(height * 0.5)));
                g.Transform = m;
                drawBrush.Color = Color.FromArgb(RandomUtils.GetRandomNumber(150) + fixedNumber + 20, RandomUtils.GetRandomNumber(150) + fixedNumber + 20, RandomUtils.GetRandomNumber(150) + fixedNumber + 20);
                PointF drawPoint = new PointF(0.0F + RandomUtils.GetRandomNumber(4) + x * 20, 3.0F + RandomUtils.GetRandomNumber(3));
                g.DrawString(RandomUtils.GetRandomNumber(1) == 1 ? code[x].ToString() : code[x].ToString().ToUpper(), fonts[RandomUtils.GetRandomNumber(fonts.Length - 1)], drawBrush, drawPoint);
                g.ResetTransform();
            }

            double distort = RandomUtils.GetRandomNumber(5, 10) * (RandomUtils.GetRandomNumber(10) == 1 ? 1 : -1);

            using (Bitmap copy = (Bitmap)bitmap.Clone())
            {
                for (int y = 0; y < height; y++)
                {
                    for (int x = 0; x < width; x++)
                    {
                        int newX = (int)(x + (distort * Math.Sin(Math.PI * y / 84.5)));
                        int newY = (int)(y + (distort * Math.Cos(Math.PI * x / 54.5)));
                        if (newX < 0 || newX >= width)
                            newX = 0;
                        if (newY < 0 || newY >= height)
                            newY = 0;
                        bitmap.SetPixel(x, y, copy.GetPixel(newX, newY));
                    }
                }
            }
            drawBrush.Dispose();
            g.Dispose();

            return bitmap;
        }
        /// <summary>
        /// Draws the shape's shadow.
        /// </summary>
        /// <remarks>
        /// The shadow is replaced with a glow.
        /// </remarks>
        protected override void DoPaintShadow(DiagramPaintEventArgs e, IGeometryHost geometryHost)
        {
            Guard.NotNull(() => geometryHost, geometryHost);
            Guard.NotNull(() => e, e);

            Graphics graphics = e.Graphics;
            GraphicsState state = graphics.Save();
            SizeD shadowOffset = this.ShadowOffset;
            try
            {
                GraphicsPath shapePath = this.GetPath(geometryHost);
                RectangleF shapeRectangle = shapePath.GetBounds();

                // Create shadow path
                GraphicsPath shadowPath = shapePath.Clone() as GraphicsPath;

                // Enlarge the shadow (by fixed magnifier amount)
                using (Matrix scaleMatrix = new Matrix())
                {
                    scaleMatrix.Scale(
                        (ShadowMagnifier / shapeRectangle.Width) + 1,
                        (ShadowMagnifier / shapeRectangle.Height) + 1);
                    shadowPath.Transform(scaleMatrix);

                    // Center shadow back on the shape
                    RectangleF shadowRectangle = shadowPath.GetBounds();
                    scaleMatrix.Reset();
                    scaleMatrix.Translate(
                        -((shadowRectangle.X + (shadowRectangle.Width / 2)) - (shapeRectangle.X + (shapeRectangle.Width / 2))),
                        -((shadowRectangle.Y + (shadowRectangle.Height / 2)) - (shapeRectangle.Y + (shapeRectangle.Height / 2))));
                    shadowPath.Transform(scaleMatrix);
                }

                // Set the clip region (on the shape)
                using (Region clip = graphics.Clip)
                {
                    graphics.SetClip(shapePath);

                    // Offset the shadow path (move diagonally down-right) from shape
                    using (Matrix translateMatrix = new Matrix())
                    {
                        translateMatrix.Translate((float)shadowOffset.Width, (float)shadowOffset.Height);
                        shadowPath.Transform(translateMatrix);
                    }

                    // Mask-off the shadow from the original shape
                    graphics.SetClip(shadowPath, CombineMode.Complement);
                    graphics.SetClip(clip, CombineMode.Intersect);

                    // Fill the shadow
                    using (PathGradientBrush shadowBrush = new PathGradientBrush(shadowPath))
                    {
                        shadowBrush.CenterColor = Color.FromArgb(ShadowColorOpacity, ShadowColor);
                        shadowBrush.SurroundColors = new Color[] { Color.Transparent };
                        shadowBrush.FocusScales = new PointF(ShadowGradientFocalPoint, ShadowGradientFocalPoint);
                        graphics.FillPath(shadowBrush, shadowPath);
                        graphics.ResetClip();
                    }
                }
            }
            finally
            {
                graphics.Restore(state);
            }
        }
Example #33
0
        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);

            if (!tracking)
            {
                Cursor cursor = this.moveToolCursor;

                for (int i = 0; i < this.moveNubs.Length; ++i)
                {
                    MoveNubRenderer nub = this.moveNubs[i];

                    if (nub.Visible && nub.IsPointTouching(new Point(e.X, e.Y), true))
                    {
                        cursor = this.handCursor;
                        break;
                    }
                }

                this.Cursor = cursor;
            }
            else
            {
                if (this.context.currentMode != Mode.Translate)
                {
                    this.Cursor = this.handCursorMouseDown;
                }

                Point newMouseXY = new Point(e.X, e.Y);
                Point newOffset = new Point(newMouseXY.X - context.startMouseXY.X, newMouseXY.Y - context.startMouseXY.Y);

                PreRender();

                this.dontDrop = true;

                Selection.PerformChanging();

                using (Matrix translateMatrix = new Matrix())
                {
                    RectangleF rect;
                    translateMatrix.Reset();

                    if (this.context.baseTransform != null)
                    {
                        Selection.SetInterimTransform(this.context.baseTransform);
                    }

                    Matrix interim = Selection.GetInterimTransformCopy();

                    switch (this.context.currentMode)
                    {
                        case Mode.Translate:
                            translateMatrix.Translate((float)newOffset.X, (float)newOffset.Y, MatrixOrder.Append);
                            break;

                        case Mode.Rotate:
                            rect = this.context.liftedBounds;
                            PointF center = new PointF(rect.X + (rect.Width / 2.0f), rect.Y + (rect.Height / 2.0f));
                            center = Utility.TransformOnePoint(interim, center);
                            double theta1 = Math.Atan2(context.startMouseXY.Y - center.Y, context.startMouseXY.X - center.X);
                            double theta2 = Math.Atan2(e.Y - center.Y, e.X - center.X);
                            double thetaDelta = theta2 - theta1;
                            this.angleDelta = (float)(thetaDelta * (180.0f / Math.PI));
                            float angle = this.context.startAngle + this.angleDelta;

                            if ((ModifierKeys & Keys.Shift) != 0)
                            {
                                angle = ConstrainAngle(angle);
                                angleDelta = angle - this.context.startAngle;
                            }

                            translateMatrix.RotateAt(angleDelta, center, MatrixOrder.Append);
                            this.rotateNub.Location = center;
                            this.rotateNub.Angle = this.context.startAngle + angleDelta;
                            break;

                        case Mode.Scale:
                            PointF xyAxes = GetEdgeVector(this.context.startEdge);
                            PointF xAxis = new PointF(xyAxes.X, 0);
                            PointF yAxis = new PointF(0, xyAxes.Y);
                            PointF edgeX = Utility.TransformOneVector(interim, xAxis);
                            PointF edgeY = Utility.TransformOneVector(interim, yAxis);
                            PointF edgeXN = Utility.NormalizeVector2(edgeX);
                            PointF edgeYN = Utility.NormalizeVector2(edgeY);

                            PointF xu;
                            float xulen;
                            PointF xv;
                            Utility.GetProjection((PointF)newOffset, edgeXN, out xu, out xulen, out xv);

                            PointF yu;
                            float yulen;
                            PointF yv;
                            Utility.GetProjection((PointF)newOffset, edgeYN, out yu, out yulen, out yv);

                            PdnGraphicsPath startPath2 = this.context.startPath.Clone();
                            RectangleF sp2Bounds = startPath2.GetBounds();

                            PointF sp2BoundsCenter = new PointF((sp2Bounds.Left + sp2Bounds.Right) / 2.0f,
                                (sp2Bounds.Top + sp2Bounds.Bottom) / 2.0f);

                            float tAngle = Utility.GetAngleOfTransform(interim);
                            bool isFlipped = Utility.IsTransformFlipped(interim);

                            using (Matrix spm = new Matrix())
                            {
                                spm.Reset();
                                spm.RotateAt(-tAngle, sp2BoundsCenter, MatrixOrder.Append);
                                translateMatrix.RotateAt(-tAngle, sp2BoundsCenter, MatrixOrder.Append);
                                startPath2.Transform(spm);
                            }

                            RectangleF spBounds2 = startPath2.GetBounds();

                            startPath2.Dispose();
                            startPath2 = null;

                            float xTranslate;
                            float yTranslate;
                            bool allowConstrain;

                            Edge theEdge = this.context.startEdge;

                            // If the transform is flipped, then GetTransformAngle will return 180 degrees
                            // even though no rotation has actually taken place. Thus we have to scratch
                            // our head and go "hmm, let's make some adjustments to this." Otherwise stretching
                            // the top and bottom nubs goes in the wrong direction.
                            if (isFlipped)
                            {
                                theEdge = FlipEdgeVertically(theEdge);
                            }

                            switch (theEdge)
                            {
                                default:
                                    throw new InvalidEnumArgumentException();

                                case Edge.TopLeft:
                                    allowConstrain = true;
                                    xTranslate = -spBounds2.X - spBounds2.Width;
                                    yTranslate = -spBounds2.Y - spBounds2.Height;
                                    break;

                                case Edge.Top:
                                    allowConstrain = false;
                                    xTranslate = 0;
                                    yTranslate = -spBounds2.Y - spBounds2.Height;
                                    break;

                                case Edge.TopRight:
                                    allowConstrain = true;
                                    xTranslate = -spBounds2.X;
                                    yTranslate = -spBounds2.Y - spBounds2.Height;
                                    break;

                                case Edge.Left:
                                    allowConstrain = false;
                                    xTranslate = -spBounds2.X - spBounds2.Width;
                                    yTranslate = 0;
                                    break;

                                case Edge.Right:
                                    allowConstrain = false;
                                    xTranslate = -spBounds2.X;
                                    yTranslate = 0;
                                    break;

                                case Edge.BottomLeft:
                                    allowConstrain = true;
                                    xTranslate = -spBounds2.X - spBounds2.Width;
                                    yTranslate = -spBounds2.Y;
                                    break;

                                case Edge.Bottom:
                                    allowConstrain = false;
                                    xTranslate = 0;
                                    yTranslate = -spBounds2.Y;
                                    break;

                                case Edge.BottomRight:
                                    allowConstrain = true;
                                    xTranslate = -spBounds2.X;
                                    yTranslate = -spBounds2.Y;
                                    break;
                            }

                            translateMatrix.Translate(xTranslate, yTranslate, MatrixOrder.Append);

                            float newWidth = spBounds2.Width + xulen;
                            float newHeight = spBounds2.Height + yulen;
                            float xScale = newWidth / spBounds2.Width;
                            float yScale = newHeight / spBounds2.Height;

                            if (allowConstrain && (this.ModifierKeys & Keys.Shift) != 0)
                            {
                                ConstrainScaling(this.context.liftedBounds, spBounds2.Width, spBounds2.Height,
                                    newWidth, newHeight, out xScale, out yScale);
                            }

                            translateMatrix.Scale(xScale, yScale, MatrixOrder.Append);
                            translateMatrix.Translate(-xTranslate, -yTranslate, MatrixOrder.Append);
                            translateMatrix.RotateAt(+tAngle, sp2BoundsCenter, MatrixOrder.Append);

                            break;

                        default:
                            throw new InvalidEnumArgumentException();
                    }

                    this.context.deltaTransform.Reset();
                    this.context.deltaTransform.Multiply(this.context.liftTransform, MatrixOrder.Append);
                    this.context.deltaTransform.Multiply(translateMatrix, MatrixOrder.Append);

                    translateMatrix.Multiply(this.context.baseTransform, MatrixOrder.Prepend);

                    Selection.SetInterimTransform(translateMatrix);

                    interim.Dispose();
                    interim = null;
                }

                // advertise our angle of rotation to any host (i.e. mainform) that might want to use that information
                this.hostShouldShowAngle = this.rotateNub.Visible;
                this.hostAngle = -this.rotateNub.Angle;

                Selection.PerformChanged();
                dontDrop = false;

                Render(newOffset, true);
                Update();

                this.context.offset = newOffset;

                if (this.enableOutline)
                {
                    DocumentWorkspace.ResetOutlineWhiteOpacity();
                }
            }
        }
Example #34
0
		internal static float ConvertSweepAngle(float sweepAngle, float startAngle, SpatialTransform transform, CoordinateSystem targetSystem)
		{
			PointF x = new PointF(100, 0);

			PointF[] startVector = new PointF[] { x };
			Matrix rotation = new Matrix();
			rotation.Rotate(startAngle);
			rotation.TransformVectors(startVector);

			PointF[] sweepVector = (PointF[])startVector.Clone();
			rotation.Reset();
			rotation.Rotate(sweepAngle);
			rotation.TransformVectors(sweepVector);
			rotation.Dispose();

			SizeF startVectorTransformed, sweepVectorTransformed;
			if (targetSystem == Graphics.CoordinateSystem.Destination)
			{
				startVectorTransformed = transform.ConvertToDestination(new SizeF(startVector[0]));
				sweepVectorTransformed = transform.ConvertToDestination(new SizeF(sweepVector[0]));
			}
			else
			{
				startVectorTransformed = transform.ConvertToSource(new SizeF(startVector[0]));
				sweepVectorTransformed = transform.ConvertToSource(new SizeF(sweepVector[0]));
			}

			// simply return the angle between the start and sweep angle, in the target system.
			return (int)Math.Round(Vector.SubtendedAngle(sweepVectorTransformed.ToPointF(), PointF.Empty, startVectorTransformed.ToPointF()));
		}
Example #35
0
        /// <summary>创建验证码图片</summary>
        /// <param name="verifyCodeImageInfo">验证码图片信息</param>
        public void CreateVerifyCodeImage(VerifyCodeImageInfo verifyCodeImageInfo)
        {
            int textLength = verifyCodeImageInfo.Text.Length;
            if(textLength == 0 || verifyCodeImageInfo.ImageWidth == 0 || verifyCodeImageInfo.ImageHeight == 0) return;

            using(var img = new Bitmap(verifyCodeImageInfo.ImageWidth, verifyCodeImageInfo.ImageHeight, PixelFormat.Format32bppArgb))
            {
                using(var g = Graphics.FromImage(img))
                {
                    g.SmoothingMode = SmoothingMode.AntiAlias;
                    g.Clear(verifyCodeImageInfo.BackgroundColor);

                    int charSize = (int)(Math.Min(verifyCodeImageInfo.ImageHeight, (int)(verifyCodeImageInfo.ImageWidth / textLength)) * 0.8);
                    PointF charPoint = new PointF();
                    int halfCharSize = (int)(charSize * 0.5f);
                    int paddingHeight = (int)(verifyCodeImageInfo.ImageHeight * 0.6) - charSize;

                    using(var matrix = new Matrix())
                    {
                        using(var pen = new Pen(Color.Empty))
                        {
                            pen.Width = 1f;
                            using(var b = new SolidBrush(verifyCodeImageInfo.TextColor))
                            {
                                using(var format = new StringFormat())
                                {
                                    format.Alignment = StringAlignment.Near;
                                    format.LineAlignment = StringAlignment.Near;
                                    Font f;
                                    for(int i = 0; i < textLength; i++)
                                    {
                                        // 位置
                                        charPoint.X += i == 0 ? charSize * 0.2f : charSize * 1.1f;// (float)(i * charSize);
                                        charPoint.Y = (float)Utils.Rand(4, paddingHeight);
                                        // 旋转
                                        matrix.Reset();
                                        matrix.RotateAt((float)Utils.Rand(-20, 20),
                                            new PointF(charPoint.X + halfCharSize, charPoint.Y + halfCharSize));
                                        //matrix.Translate(charPoint.X, charPoint.Y);
                                        g.Transform = matrix;

                                        b.Color = pen.Color = GetTextColor(verifyCodeImageInfo.RandomTextColor, verifyCodeImageInfo.TextColor);

                                        // 字符大小
                                        float fs = charSize * Utils.Rand(80, 120) * 0.01f;
                                        f = new Font(GetFontFamily(verifyCodeImageInfo.Fonts), fs);

                                        g.DrawString(verifyCodeImageInfo.Text[i].ToString(), f, b, charPoint, format);
                                        f.Dispose();
                                        g.ResetTransform();

                                        // 使用字符相同颜色随机绘制曲线
                                        //pen.Width = Utils.Rand(1, 2);
                                        g.DrawBezier(pen,
                                            Utils.Rand(verifyCodeImageInfo.ImageWidth),
                                            Utils.Rand(verifyCodeImageInfo.ImageHeight),
                                            Utils.Rand(verifyCodeImageInfo.ImageWidth),
                                            Utils.Rand(verifyCodeImageInfo.ImageHeight),
                                            Utils.Rand(verifyCodeImageInfo.ImageWidth),
                                            Utils.Rand(verifyCodeImageInfo.ImageHeight),
                                            Utils.Rand(verifyCodeImageInfo.ImageWidth),
                                            Utils.Rand(verifyCodeImageInfo.ImageHeight));

                                    }

                                    // 绘制随机纵向曲线
                                    pen.Color = GetTextColor(verifyCodeImageInfo.RandomTextColor, verifyCodeImageInfo.TextColor);
                                    //pen.Width = Utils.Rand(1, 2);
                                    g.DrawBezier(pen,
                                        Utils.Rand(verifyCodeImageInfo.ImageWidth),
                                        0,
                                        Utils.Rand(verifyCodeImageInfo.ImageWidth),
                                        Utils.Rand(verifyCodeImageInfo.ImageHeight),
                                        Utils.Rand(verifyCodeImageInfo.ImageWidth),
                                        Utils.Rand(verifyCodeImageInfo.ImageHeight),
                                        Utils.Rand(verifyCodeImageInfo.ImageWidth),
                                        verifyCodeImageInfo.ImageHeight);
                                    // 绘制随机横向曲线
                                    //pen.Width = Utils.Rand(1, 2);
                                    pen.Color = GetTextColor(verifyCodeImageInfo.RandomTextColor, verifyCodeImageInfo.TextColor);
                                    g.DrawBezier(pen,
                                        0,
                                        Utils.Rand(verifyCodeImageInfo.ImageHeight),
                                        Utils.Rand(verifyCodeImageInfo.ImageWidth),
                                        Utils.Rand(verifyCodeImageInfo.ImageHeight),
                                        Utils.Rand(verifyCodeImageInfo.ImageWidth),
                                        Utils.Rand(verifyCodeImageInfo.ImageHeight),
                                        verifyCodeImageInfo.ImageWidth,
                                        Utils.Rand(verifyCodeImageInfo.ImageHeight));

                                }
                            }
                        }
                    }
                }
                verifyCodeImageInfo.ImageData = img.Clone() as Image;
            }
        }
Example #36
0
        public void OnLoad(EventArgs e)
        {
            Bitmap bmp = new Bitmap(this.Height*0x06, this.Height*0x02);
            Graphics g = Graphics.FromImage(bmp);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            float w = 6.0f*this.Height;
            int hInt = this.Height;
            float h = (float)hInt;
            float margin = h/48.0f;
            float m2 = 2.0f*margin;
            float r = h/36.0f;///36.0f
            float r2 = 2.0f*r;
            float h_2 = 0.5f*h;
            float Ro = h_2-margin;
            float alpha = (float)(180.0d/Math.PI*Math.Acos(1.0d-0.5d*r/Ro));
            float beta = (float)(180.0d/Math.PI*Math.Acos(1.0d-r/Ro));
            float betaY = (float)Math.Sqrt(Ro*Ro-(Ro-r)*(Ro-r));
            float sqrtR2 = (float)(Math.Sqrt(0.5d)*(h-m2-r2));
            float __R2 = h_2-margin-r;
            __R2 *= __R2;
            for(int l = 0x00; l < 0x02; l++) {
                using(GraphicsPath gpNocturne = new GraphicsPath()) {
                    //left wing
                    gpNocturne.AddArc(0.5f*w-h+m2, margin, h-m2, h-m2, 180.0f+alpha, 360.0f-2.0f*alpha);
                    gpNocturne.AddArc(0.5f*w+2.0f*(m2-h)+r, margin, h-m2, h-m2, alpha, 90.0f-alpha);
                    gpNocturne.AddLine(0.5f*w+1.5f*m2+r-1.5f*h, h-margin, h_2, h-margin);
                    gpNocturne.AddArc(margin, margin, h-m2, h-m2, 90.0f, 90.0f-beta);
                    gpNocturne.AddLine(margin+r, h_2+betaY, margin+r, h-margin);
                    gpNocturne.AddLine(margin+r, h-margin, margin, h-margin);
                    gpNocturne.AddLine(margin, h-margin, margin, margin);
                    gpNocturne.AddLine(margin, margin, margin+r, margin);
                    gpNocturne.AddLine(margin+r, margin, margin+r, h_2-betaY);
                    gpNocturne.AddArc(margin, margin, h-m2, h-m2, 180.0f+beta, 90.0f-beta);
                    gpNocturne.AddLine(h_2, margin, 0.5f*w+1.5f*m2+r-1.5f*h, margin);
                    gpNocturne.AddArc(0.5f*w+2.0f*(m2-h)+r, margin, h-m2, h-m2, 270.0f, 90.0f-alpha);
                    gpNocturne.CloseFigure();
                    //right wing
                    gpNocturne.AddArc(0.5f*w, margin, h-m2, h-m2, 360.0f-alpha, 2.0f*alpha-360.0f);
                    gpNocturne.AddArc(0.5f*w+h-m2-r, margin, h-m2, h-m2, 180.0f-alpha, alpha-90.0f);
                    gpNocturne.AddLine(0.5f*w+2.0f*(h-m2)-r, h-margin, w-h_2, h-margin);
                    gpNocturne.AddArc(w-h+margin, margin, h-m2, h-m2, 90.0f, beta-90.0f);
                    gpNocturne.AddLine(w-margin-r, h_2+betaY, w-margin-r, h-margin);
                    gpNocturne.AddLine(w-margin-r, h-margin, w-margin, h-margin);
                    gpNocturne.AddLine(w-margin, h-margin, w-margin, margin);
                    gpNocturne.AddLine(w-margin, margin, w-margin-r, margin);
                    gpNocturne.AddLine(w-margin-r, margin, w-margin-r, h_2-betaY);
                    gpNocturne.AddArc(w-h+margin, margin, h-m2, h-m2, -beta, beta-90.0f);
                    gpNocturne.AddLine(w-h_2, margin, 0.5f*w+2.0f*(h-m2)-r, margin);
                    gpNocturne.AddArc(0.5f*w+h-m2-r, margin, h-m2, h-m2, 270.0f, alpha-90.0f);
                    gpNocturne.CloseFigure();
                    if(l == 0x00)
                        g.FillPath(EgyptInformation.Brushes.EgyptNocturne, gpNocturne);
                    else
                        g.FillPath(EgyptInformation.Brushes.EgyptPaintBlue, gpNocturne);
                    //g.FillPath(new SolidBrush(Color.FromArgb(0x4c,0x41,0x0b)),gpNocturne);
                    using(GraphicsPath gpGold = new GraphicsPath()) {
                        gpGold.AddPath(gpNocturne, false);
                        //left inner
                        gpGold.AddArc(margin+r, margin+r, h-m2-r2, h-m2-r2, 90.0f, 180.0f);
                        gpGold.AddArc(0.5f*w+2.0f*(m2-h)+r2, margin+r, h-m2-r2, h-m2-r2, 270.0f, 180.0f);
                        gpGold.CloseFigure();
                        //left ellipse
                        gpGold.AddEllipse(0.5f*w-h+m2+r, margin+r, h-m2-r2, h-m2-r2);
                        gpGold.CloseFigure();
                        //right inner
                        gpGold.AddArc(w-h+margin+r, margin+r, h-m2-r2, h-m2-r2, 90.0f, -180.0f);
                        gpGold.AddArc(0.5f*w+h-m2, margin+r, h-m2-r2, h-m2-r2, 270.0f, -180.0f);
                        gpGold.CloseFigure();
                        //right ellipse
                        gpGold.AddEllipse(0.5f*w+r, margin+r, h-m2-r2, h-m2-r2);
                        gpGold.CloseFigure();
                        g.FillPath(EgyptInformation.Brushes.EgyptGold, gpGold);
                        GraphicsUtils.DrawGlass(g, gpGold);
                    }
                    Matrix M = new Matrix();
                    M.Scale(sqrtR2, sqrtR2);
                    RectangleF bounds;
                    Matrix Mtrans = new Matrix();
                    GraphicsPath gpHedjet = EgyptInformation.GraphicsPaths.Hedjet();
                    gpHedjet.Transform(M);
                    bounds = gpHedjet.GetBounds();
                    Mtrans.Translate(-0.5f*bounds.Width, 0.0f);
                    Mtrans.Scale(-1.0f, 1.0f, MatrixOrder.Append);
                    Mtrans.Translate(0.5f*(w-h+m2), h_2-0.5f*bounds.Height, MatrixOrder.Append);
                    gpHedjet.Transform(Mtrans);
                    g.FillPath(EgyptInformation.Brushes.EgyptPaintWhite, gpHedjet);
                    GraphicsUtils.DrawGlass(g, gpHedjet);
                    GraphicsPath gpDeshret = EgyptInformation.GraphicsPaths.Deshret();
                    gpDeshret.Transform(M);
                    bounds = gpDeshret.GetBounds();
                    Mtrans.Reset();
                    Mtrans.Translate(0.5f*(w+h-m2-bounds.Width), h_2-0.5f*bounds.Height);
                    gpDeshret.Transform(Mtrans);
                    g.FillPath(EgyptInformation.Brushes.EgyptPaintRed, gpDeshret);
                    GraphicsUtils.DrawGlass(g, gpDeshret);
                }
                g.TranslateTransform(0.0f, h);
            }
            BitmapData bmd = bmp.LockBits(new Rectangle(0x00, 0x00, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            this.texturePointer = GL.GenTexture();
            GL.BindTexture(TextureTarget.Texture2D, this.texturePointer);
            GL.TexEnv(TextureEnvTarget.TextureEnv, TextureEnvParameter.TextureEnvMode, (float)TextureEnvMode.Modulate);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (float)TextureMinFilter.LinearMipmapLinear);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (float)TextureMagFilter.Linear);
            Glu.Glu.Build2DMipmap(Glu.TextureTarget.Texture2D, (int)PixelInternalFormat.Four, bmp.Width, bmp.Height, OpenTK.Graphics.PixelFormat.Bgra, Glu.PixelType.UnsignedByte, bmd.Scan0);
            bmp.UnlockBits(bmd);
        }
Example #37
0
        public Bitmap Generate(string sCaptchaText)
        {
            int    iHeight = 80;
            int    iWidth  = 190;
            Random oRandom = new Random();

            int[] aBackgroundNoiseColor = new int[] { 150, 150, 150 };
            int[] aTextColor            = new int[] { 0, 0, 0 };
            int[] aFontEmSizes          = new int[] { 25, 25, 25, 25, 25 };

            string[] aFontNames = new string[]
            {
                "Arial"
            };

            FontStyle[] aFontStyles = new FontStyle[]
            {
                FontStyle.Bold,
                FontStyle.Bold,
                FontStyle.Bold,
                FontStyle.Bold,
                FontStyle.Bold
            };

            HatchStyle[] aHatchStyles = new HatchStyle[]
            {
                HatchStyle.Cross
            };

            //string sCaptchaText = GetCaptchaString(6);
            //context.HttpContext.Session["captchastring"] = sCaptchaText;

            //Creates an output Bitmap
            Bitmap   oOutputBitmap = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb);
            Graphics oGraphics     = Graphics.FromImage(oOutputBitmap);

            oGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;

            //Create a Drawing area
            RectangleF oRectangleF = new RectangleF(0, 0, iWidth, iHeight);
            Brush      oBrush      = default(Brush);

            //Draw background (Lighter colors RGB 100 to 255)
            oBrush = new HatchBrush(aHatchStyles[oRandom.Next(aHatchStyles.Length - 1)], Color.FromArgb((oRandom.Next(100, 255)), (oRandom.Next(100, 255)), (oRandom.Next(100, 255))), Color.White);
            oGraphics.FillRectangle(oBrush, oRectangleF);

            System.Drawing.Drawing2D.Matrix oMatrix = new System.Drawing.Drawing2D.Matrix();
            int i = 0;

            for (i = 0; i <= sCaptchaText.Length - 1; i++)
            {
                sCaptchaText = sCaptchaText.ToUpper();

                oMatrix.Reset();
                int iChars = sCaptchaText.Length;
                int x      = iWidth / (iChars + 1) * i;
                int y      = iHeight / 2;

                //Rotate text Random
                oMatrix.RotateAt(oRandom.Next(-20, 20), new PointF(x, y));
                oGraphics.Transform = oMatrix;

                //Draw the letters with Randon Font Type, Size and Color
                oGraphics.DrawString
                (
                    //Text
                    sCaptchaText.Substring(i, 1),
                    //Random Font Name and Style
                    new Font(aFontNames[oRandom.Next(aFontNames.Length - 1)], aFontEmSizes[oRandom.Next(aFontEmSizes.Length - 1)], aFontStyles[oRandom.Next(aFontStyles.Length - 1)]),
                    //Random Color (Darker colors RGB 0 to 100)
                    new SolidBrush(Color.FromArgb(oRandom.Next(0, 100), oRandom.Next(0, 100), oRandom.Next(0, 100))),
                    x,
                    oRandom.Next(10, 40)
                );

                oGraphics.ResetTransform();
            }

            return(oOutputBitmap);
        }
Example #38
0
        static void Main(string[] args)
        {
            for (int i = 0; i < args.Length; i++)
            {
                switch (args[i])
                {
                    case "/proc":
                        if (i + 1 == args.Length)
                        {
                            Console.WriteLine("Use /proc <N> to specify number of processors");
                            return;
                        }

                        int numProcs;

                        if (Int32.TryParse(args[i + 1], out numProcs))
                        {
                            // only increment i if successful b/c we're going to continue the run
                            // with the default # of processors and don't want to automatically 
                            // eat the next parameter.
                            ++i;
                            Processor.LogicalCpuCount = numProcs;
                        }
                        else
                        {
                            Console.WriteLine("You must specify a integer for /proc <N>, continuing with default");
                        }
                        break;

                    case "/image":
                        if (i + 1 == args.Length)
                        {
                            Console.WriteLine("Use /image <filename> to specify a file to perform benchmark with");
                            return;
                        }

                        ++i;
                        benchmarkImageName = args[i];

                        if (!System.IO.File.Exists(benchmarkImageName))
                        {
                            Console.WriteLine("Specified image doesn't exist");
                            return;
                        }
                        break;

                    case "/tsv":
                        useTsvOutput = true;
                        break;

                    case "/?":
                        PrintHelp();
                        return;

                    default:
                        break;
                }
            }

            //Processor.LogicalCpuCount = 1;
            Console.WriteLine("PdnBench v" + PdnInfo.GetVersion());
            Console.WriteLine("Running in " + (8 * Marshal.SizeOf(typeof(IntPtr))) + "-bit mode on Windows " +
                Environment.OSVersion.Version.ToString() + " " +
                OS.Revision + (OS.Revision.Length > 0 ? " " : string.Empty) +
                OS.Type + " " +
                Processor.NativeArchitecture.ToString().ToLower());

            Console.WriteLine("Processor: " + Processor.LogicalCpuCount + "x \"" + Processor.CpuName + "\" @ ~" + GetCpuSpeed() + " MHz");
            Console.WriteLine("Memory: " + ((Memory.TotalPhysicalBytes / 1024) / 1024) + " MB");
            Console.WriteLine();

            Console.WriteLine("Using " + Processor.LogicalCpuCount + " threads.");

            ArrayList benchmarks = new ArrayList();

            Document document;

            Console.Write("Loading image ... ");

            Stream imageStream = null;
            try
            {
                imageStream = (defaultImageName == benchmarkImageName) ?
                    Assembly.GetExecutingAssembly().GetManifestResourceStream(benchmarkImageName) :
                    new FileStream(benchmarkImageName, FileMode.Open);

                JpegFileType jft = new JpegFileType();
                document = jft.Load(imageStream);
            }

            finally
            {
                if (imageStream != null)
                {
                    imageStream.Dispose();
                }
            }

            Console.WriteLine("(" + document.Width + " x " + document.Height + ") done");

            Surface surface = ((BitmapLayer)document.Layers[0]).Surface;

#if EFFECTS
            for (double i = 0; i < (2 * Math.PI); i += 70.0 * ((2 * Math.PI) / 360.0))
            {
                benchmarks.Add(
                    new EffectBenchmark("Rotate/Zoom at " + ((i * 180.0) / Math.PI).ToString("F2") + " degrees",
                    3,
                    new PaintDotNet.Effects.RotateZoomEffect(),
                    new PaintDotNet.Effects.RotateZoomEffectConfigToken(
                        true,
                        (float)(Math.PI * 0.3f),
                        (float)((Math.PI * -0.4) + i),
                        50,
                        0.5f,
                        new PointF(-0.2f, 0.3f),
                        false,
                        true),
                        surface));
            }

            for (int i = 1; i <= 4; i += 3)
            {
                for (int j = 10; j < 100; j += 75)
                {
                    benchmarks.Add(
                        new EffectBenchmark(
                            "Oil Painting, brush size = " + i + ", coarseness = " + j,
                            1,
                            new OilPaintingEffect(),
                            new TwoAmountsConfigToken(i, j),
                            surface));
                }
            }

            for (int i = 2; i <= 50; i += i)
            {
                benchmarks.Add(
                    new EffectBenchmark(
                        "Blur with radius of " + i,
                        1,
                        new BlurEffect(),
                        new AmountEffectConfigToken(i),
                        surface));
            }

            for (int i = 1; i <= 4; i += 3)
            {
                benchmarks.Add(
                    new EffectBenchmark(
                        "Sharpen with value of " + i,
                        1,
                        new SharpenEffect(),
                        new AmountEffectConfigToken(i),
                        surface));
            }

            benchmarks.Add(
                new EffectBenchmark(
                    "Auto-Levels",
                    50,
                    new AutoLevelEffect(),
                    null,
                    surface));

            for (int i = 81; i >= 5; i /= 3)
            {
                benchmarks.Add(
                    new EffectBenchmark(
                        "Clouds, roughness = " + i,
                        2,
                        new CloudsEffect(),
                        new CloudsEffectConfigToken(50, i, 12345, new UserBlendOps.NormalBlendOp()),
                        surface));
            }

            for (int i = 4; i <= 64; i *= 4)
            {
                benchmarks.Add(
                    new EffectBenchmark(
                        "Median, radius " + i,
                        1,
                        new MedianEffect(),
                        new TwoAmountsConfigToken(/*radius*/i, /*roughness*/50),
                        surface));
            }

            for (int i = 4; i <= 64; i *= 4)
            {
                benchmarks.Add(
                   new EffectBenchmark(
                       "Unfocus, radius " + i,
                       1,
                       new UnfocusEffect(),
                       new AmountEffectConfigToken(i),
                        surface));
            }

            benchmarks.Add(
                new EffectBenchmark(
                    "Motion Blur, Horizontal",
                    1,
                    new MotionBlurEffect(),
                    new MotionBlurEffectConfigToken(0, 100, true),
                        surface));

            benchmarks.Add(
                new EffectBenchmark(
                    "Motion Blur, Vertical",
                    1,
                    new MotionBlurEffect(),
                    new MotionBlurEffectConfigToken(90, 100, true),
                        surface));

#endif

            Surface dst = new Surface(surface.Width * 4, surface.Height * 4);

#if RESIZE
            // Resize benchmarks
            for (int i = 1; i < 8; i += 2)
            {
                int newWidth = i * (dst.Width / 8);
                int newHeight = i * (dst.Height / 8);

                Surface dstWindow = dst.CreateWindow(new Rectangle(0, 0, newWidth, newHeight));
                benchmarks.Add(new ResizeBenchmark("Resize from " + surface.Width + "x" + surface.Height + " to " + newWidth + "x" + newHeight, surface, dstWindow));
                benchmarks.Add(new ResizeBenchmark("Resize from " + newWidth + "x" + newHeight + " to " + surface.Width + "x" + surface.Height, dstWindow, surface));
            }
#endif

#if GRADIENT
            // Gradient benchmarks
            benchmarks.Add(new GradientBenchmark(
                "Linear reflected gradient @ " + dst.Width + "x" + dst.Height + " (5x)",
                dst,
                new GradientRenderers.LinearReflected(false, new UserBlendOps.NormalBlendOp()),
                2));

            benchmarks.Add(new GradientBenchmark(
                "Conical gradient @ " + dst.Width + "x" + dst.Height + " (5x)",
                dst,
                new GradientRenderers.Conical(false, new UserBlendOps.NormalBlendOp()),
                2));

            benchmarks.Add(new GradientBenchmark(
                "Radial gradient @ " + dst.Width + "x" + dst.Height + " (5x)",
                dst,
                new GradientRenderers.Radial(false, new UserBlendOps.NormalBlendOp()),
                2));
#endif

#if COMPOSITION
            // Composition benchmarks
            Document doc1 = new Document(surface.Size);
            BitmapLayer layer1 = Layer.CreateBackgroundLayer(doc1.Width, doc1.Height);
            layer1.Surface.CopySurface(surface);
            doc1.Layers.Add(layer1);
            doc1.Layers.Add(layer1.Clone());
            doc1.Layers.Add(layer1.Clone());
            doc1.Layers.Add(layer1.Clone());

            benchmarks.Add(new CompositionBenchmark("Compositing one layer, Normal blend mode, 255 opacity (" + CompositionBenchmark.Iterations + "x)",
                doc1,
                surface,
                delegate(int layerIndex, Layer layer)
                {
                    if (layerIndex == 0)
                    {
                        layer.Visible = true;
                        layer.Opacity = 255;
                        ((BitmapLayer)layer).SetBlendOp(new UserBlendOps.NormalBlendOp());
                    }
                    else
                    {
                        layer.Visible = false;
                    }
                }));

            benchmarks.Add(new CompositionBenchmark("Compositing one layer, Normal blend mode, 128 opacity (" + CompositionBenchmark.Iterations + "x)",
                doc1,
                surface,
                delegate(int layerIndex, Layer layer)
                {
                    if (layerIndex == 0)
                    {
                        layer.Visible = true;
                        layer.Opacity = 128;
                        ((BitmapLayer)layer).SetBlendOp(new UserBlendOps.NormalBlendOp());
                    }
                    else
                    {
                        layer.Visible = false;
                    }
                }));

            benchmarks.Add(new CompositionBenchmark("Compositing four layers, Normal blend mode, 255 opacity (" + CompositionBenchmark.Iterations + "x)",
                doc1,
                surface,
                delegate(int layerIndex, Layer layer)
                {
                    layer.Visible = true;
                    layer.Opacity = 255;
                    ((BitmapLayer)layer).SetBlendOp(new UserBlendOps.NormalBlendOp());
                }));

            benchmarks.Add(new CompositionBenchmark("Compositing four layers, Normal blend mode, 255 (layer 0) and 128 (layer 1-3) opacity (" + CompositionBenchmark.Iterations + "x)", doc1, surface,
                delegate(int layerIndex, Layer layer)
                {
                    layer.Visible = true;
                    layer.Opacity = 128;
                    ((BitmapLayer)layer).SetBlendOp(new UserBlendOps.NormalBlendOp());
                }));

            benchmarks.Add(new CompositionBenchmark("Compositing four layers, Normal blend mode, 128 opacity (" + CompositionBenchmark.Iterations + "x)", doc1, surface,
                delegate(int layerIndex, Layer layer)
                {
                    layer.Visible = true;
                    layer.Opacity = 128;
                    ((BitmapLayer)layer).SetBlendOp(new UserBlendOps.NormalBlendOp());
                }));

            benchmarks.Add(new CompositionBenchmark("Compositing three layers, Normal+Multiply+Overlay blending, 150+255+170 opacity (" + CompositionBenchmark.Iterations + "x)", doc1, surface,
                delegate(int layerIndex, Layer layer)
                {
                    if (layerIndex == 0)
                    {
                        layer.Visible = true;
                        layer.Opacity = 150;
                        ((BitmapLayer)layer).SetBlendOp(new UserBlendOps.NormalBlendOp());
                    }
                    else if (layerIndex == 1)
                    {
                        layer.Visible = true;
                        layer.Opacity = 255;
                        ((BitmapLayer)layer).SetBlendOp(new UserBlendOps.MultiplyBlendOp());
                    }
                    else if (layerIndex == 2)
                    {
                        layer.Visible = true;
                        layer.Opacity = 170;
                        ((BitmapLayer)layer).SetBlendOp(new UserBlendOps.OverlayBlendOp());
                    }
                    else
                    {
                        layer.Visible = false;
                    }
                }));
#endif

#if TRANSFORM
            // Transform benchmarks
            Matrix m = new Matrix();
            m.Reset();

            MaskedSurface msSimple = new MaskedSurface(surface, new PdnRegion(surface.Bounds)); // simple masked surface

            PdnRegion complexRegion = new PdnRegion(surface.Bounds);

            // cut 4 holes in region 1 to form a complex clipping surface
            for (int x = -1; x < 3; ++x)
            {
                for (int y = -1; y < 3; ++y)
                {
                    int left = (1 + (x * 3)) * (surface.Width / 6);
                    int top = (1 + (x * 3)) * (surface.Height / 6);
                    int right = (2 + (x * 3)) * (surface.Width / 6);
                    int bottom = (2 + (x * 3)) * (surface.Height / 6);

                    Rectangle rect = Rectangle.FromLTRB(left, top, right, bottom);
                    PdnGraphicsPath path = new PdnGraphicsPath();
                    path.AddEllipse(rect);
                    complexRegion.Exclude(path);
                }
            }

            MaskedSurface msComplex = new MaskedSurface(surface, complexRegion);

            benchmarks.Add(new TransformBenchmark("Transform simple surface, no transform, nearest neighbor resampling (" + TransformBenchmark.Iterations + "x)",
                surface,
                msSimple,
                m,
                false));

            benchmarks.Add(new TransformBenchmark("Transform complex surface, no transform, nearest neighbor resampling (" + TransformBenchmark.Iterations + "x)",
                surface,
                msSimple,
                m,
                false));

            benchmarks.Add(new TransformBenchmark("Transform simple surface, no transform, bilinear resampling (" + TransformBenchmark.Iterations + "x)",
                surface,
                msSimple,
                m,
                true));

            benchmarks.Add(new TransformBenchmark("Transform complex surface, no transform, bilinear resampling (" + TransformBenchmark.Iterations + "x)",
                surface,
                msSimple,
                m,
                true));

            Matrix m2 = m.Clone();
            m2.RotateAt(45.0f, new PointF(surface.Width / 2, surface.Height / 2));

            benchmarks.Add(new TransformBenchmark("Transform simple surface, 45 deg. rotation about center, bilinear resampling (" + TransformBenchmark.Iterations + "x)",
                surface,
                msSimple,
                m2,
                true));

            benchmarks.Add(new TransformBenchmark("Transform complex surface, 45 deg. rotation about center, bilinear resampling (" + TransformBenchmark.Iterations + "x)",
                surface,
                msSimple,
                m2,
                true));

            Matrix m3 = m.Clone();
            m3.Scale(0.5f, 0.75f);

            benchmarks.Add(new TransformBenchmark("Transform simple surface, 50% x-scaling 75% y-scaling, bilinear resampling (" + TransformBenchmark.Iterations + "x)",
                surface,
                msSimple,
                m3,
                true));

            benchmarks.Add(new TransformBenchmark("Transform complex surface, 50% x-scaling 75% y-scaling, bilinear resampling (" + TransformBenchmark.Iterations + "x)",
                surface,
                msSimple,
                m3,
                true));
#endif

#if BLIT
            // Blit benchmarks
            benchmarks.Add(new ZoomOutBlitBenchmark("Zoom out, rotated grid multisampling, 66% (" + ZoomOutBlitBenchmark.IterationCount + "x)",
                surface,
                dst,
                new Size((surface.Width * 2) / 3, (surface.Height * 2) / 3)));

            benchmarks.Add(new ZoomOutBlitBenchmark("Zoom out, rotated grid multisampling, 28% (" + ZoomOutBlitBenchmark.IterationCount + "x)",
                surface,
                dst,
                new Size((surface.Width * 28) / 100, (surface.Height * 28) / 100)));

            benchmarks.Add(new ZoomOneToOneBlitBenchmark("Zoom 1:1, straight blit (" + ZoomOneToOneBlitBenchmark.IterationCount + "x)",
                surface,
                dst.CreateWindow(new Rectangle(0, 0, surface.Width, surface.Height))));
#endif

            // Run benchmarks!
            Timing timing = new Timing();
            ulong start = timing.GetTickCount();

            foreach (Benchmark benchmark in benchmarks)
            {
                Console.Write(benchmark.Name + (useTsvOutput ? "\t" : " ... "));
                TimeSpan timeSpan = benchmark.Execute();
                Console.WriteLine(" " + timeSpan.TotalMilliseconds.ToString() + (useTsvOutput ? "\t" : "") + " milliseconds");

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

            ulong end = timing.GetTickCount();

            Console.WriteLine();
            Console.WriteLine("Total time: " + (useTsvOutput ? "\t" : "") + (end - start).ToString() + (useTsvOutput ? "\t" : "") + " milliseconds");
            Console.WriteLine();
        }
Example #39
0
        public static Bitmap DrawShadowBitmap(int width, int height, int borderRadius, int blur, int spread, Color color)
        {
            int ex = blur + spread;
            int w = width + ex * 2;
            int h = height + ex * 2;
            int solidW = width + spread * 2;
            int solidH = height + spread * 2;

            var bitmap = new Bitmap(w, h);
            Graphics g = Graphics.FromImage(bitmap);
            // fill background
            g.FillRectangle(new SolidBrush(color)
                , blur, blur, width + spread * 2 + 1, height + spread * 2 + 1);
            // +1 to fill the gap

            if (blur > 0)
            {
                // four dir gradiant
                {
                    // left
                    var brush = new LinearGradientBrush(new Point(0, 0), new Point(blur, 0), Color.Transparent, color);
                    // will thorw ArgumentException
                    // brush.WrapMode = WrapMode.Clamp;

                    g.FillRectangle(brush, 0, blur, blur, solidH);
                    // up
                    brush.RotateTransform(90);
                    g.FillRectangle(brush, blur, 0, solidW, blur);

                    // right
                    // make sure parttern is currect
                    brush.ResetTransform();
                    brush.TranslateTransform(w % blur, h % blur);

                    brush.RotateTransform(180);
                    g.FillRectangle(brush, w - blur, blur, blur, solidH);
                    // down
                    brush.RotateTransform(90);
                    g.FillRectangle(brush, blur, h - blur, solidW, blur);
                }

                // four corner
                {
                    var gp = new GraphicsPath();
                    //gp.AddPie(0,0,blur*2,blur*2, 180, 90);
                    gp.AddEllipse(0, 0, blur * 2, blur * 2);

                    var pgb = new PathGradientBrush(gp);
                    pgb.CenterColor = color;
                    pgb.SurroundColors = new[] { Color.Transparent };
                    pgb.CenterPoint = new Point(blur, blur);

                    // lt
                    g.FillPie(pgb, 0, 0, blur * 2, blur * 2, 180, 90);
                    // rt
                    var matrix = new Matrix();
                    matrix.Translate(w - blur * 2, 0);

                    pgb.Transform = matrix;
                    //pgb.Transform.Translate(w-blur*2, 0);
                    g.FillPie(pgb, w - blur * 2, 0, blur * 2, blur * 2, 270, 90);
                    // rb
                    matrix.Translate(0, h - blur * 2);
                    pgb.Transform = matrix;
                    g.FillPie(pgb, w - blur * 2, h - blur * 2, blur * 2, blur * 2, 0, 90);
                    // lb
                    matrix.Reset();
                    matrix.Translate(0, h - blur * 2);
                    pgb.Transform = matrix;
                    g.FillPie(pgb, 0, h - blur * 2, blur * 2, blur * 2, 90, 90);
                }
            }

            //
            return bitmap;
        }
Example #40
0
        public MatrixComponents GetMatrixComponents()
        {
            System.Drawing.Drawing2D.Matrix srcMatrix = new System.Drawing.Drawing2D.Matrix(
                this.ScaleX,
                this.Rotate0,
                this.Rotate1,
                this.ScaleY,
                this.TranslateX,
                this.TranslateY);
            System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix(1, 0, 0, 1, 0, 0);             // identity
            // an 'identity' box
            PointF[] modPts = new PointF[] { new PointF(0, 0),
                                             new PointF(1, 0),
                                             new PointF(1, 1),
                                             new PointF(0, 1) };

            float sx, sy, rot, shear, tx, ty;

            srcMatrix.TransformPoints(modPts);

            // translation
            tx = srcMatrix.OffsetX;
            ty = srcMatrix.OffsetY;
            m.Translate(-tx, -ty);
            m.TransformPoints(modPts);
            m.Reset();

            // rotation
            rot = (float)Math.Atan2(modPts[1].Y, modPts[1].X);             // x axis
            rot = (float)(rot / Math.PI * 180);
            if (rot == -0)
            {
                rot = 0;
            }
            if (rot == -180)
            {
                rot = 180;
            }
            m.Rotate(-1 * rot);
            m.TransformPoints(modPts);
            m.Reset();

            // scale
            //sx = Dist(modPts[0], modPts[3]); // bug it seems..?
            sx = Dist(modPts[0], modPts[1]);
            sy = Dist(modPts[0], new PointF(0, modPts[3].Y));
            if (modPts[0].Y > modPts[3].Y)
            {
                sy *= -1;
            }
            m.Scale(1 / sx, 1 / sy);
            m.TransformPoints(modPts);
            m.Reset();

            // skew
            // ySkew is impossible at this rotation
            shear = modPts[3].X / Dist(modPts[0], modPts[1]);
            // rounding
            shear = Math.Abs(shear) < 0.001 ? 0 : shear;
            m.Shear(-shear, 0);
            m.TransformPoints(modPts);

            m.Dispose();
            srcMatrix.Dispose();

            return(new MatrixComponents(sx, sy, rot, shear, tx, ty));
        }
Example #41
0
 public void ResetTransform()
 {
     _transform.Reset();
 }