Shear() public method

public Shear ( float shearX, float shearY ) : void
shearX float
shearY float
return void
Example #1
0
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            using (Graphics g = e.Graphics)
            {
                // Создаем траекторию
                GraphicsPath path = new GraphicsPath();
                Rectangle rect = new Rectangle(20, 20, 150, 150);
                path.AddRectangle(rect);
                // Создаем градиентную кисть
                PathGradientBrush pgBrush =
                    new PathGradientBrush(path.PathPoints);
                // Уснинавливаем цвета кисти
                pgBrush.CenterColor = Color.Red;
                pgBrush.SurroundColors = new Color[] { Color.Blue };
                // Создаем объект Matrix
                Matrix X = new Matrix();
                // Translate
                X.Translate(30.0f, 10.0f, MatrixOrder.Append);
                // Rotate
                X.Rotate(10.0f, MatrixOrder.Append);
                // Scale
                X.Scale(1.2f, 1.0f, MatrixOrder.Append);
                // Shear
                X.Shear(.2f, 0.03f, MatrixOrder.Prepend);
                // Применяем преобразование к траектории и кисти
                path.Transform(X);
                pgBrush.Transform = X;
                // Выполняем визуализацию
                g.FillPath(pgBrush, path);
            }

        }
Example #2
0
		static public Matrix GetMatrix (int index)
		{
			// not defined (-1) or first (0)
			if (index <= 0)
				return null;

			Matrix m = new Matrix ();
			switch (index) {
			case 1:
				// empty
				break;
			case 2:
				m.Rotate (15);
				break;
			case 3:
				m.RotateAt (45, new PointF (100, 100));
				break;
			case 4:
				m.Scale (1.5f, 0.5f);
				break;
			case 5:
				m.Shear (2.0f, 2.0f);
				break;
			case 6:
				m.Translate (50, 50);
				break;
			}
			return m;
		}
Example #3
0
        /// <summary>
        /// 创建图片
        /// </summary>
        /// <param name="str"></param>
        public void CreateImage(string validateCode)
        {
            int width = validateCode.Length * 30;
            Random rand = new Random();
            Bitmap bmp = new Bitmap(width + validateCode.Length * 3, 50);

            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.FromArgb(255, 255, 255));

            DrawLine(g, bmp, RANDOM_LINE_COUNT);
            DrawPrint(bmp, RANDOM_PRINT_COUNT);

            for (int i = 0; i < validateCode.Length; i++)
            {

                Matrix matrix = new Matrix();
                matrix.Shear((float)_random.Next(0, 300) / 1000 - 0.25f, (float)_random.Next(0, 100) / 1000 - 0.05f);
                g.Transform = matrix;
                string str = validateCode.Substring(i, 1);
                LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, bmp.Width, bmp.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                Point pos = new Point(i * 30 + 1 + rand.Next(3), 1 + rand.Next(5));
                Font font = new Font(Fonts[_random.Next(Fonts.Length - 1)], _random.Next(24, 30), FontStyle.Bold);
                g.DrawString(str, font, brush, pos);
            }

            MemoryStream ms = new MemoryStream();
            bmp.Save(ms, ImageFormat.Png);
            Response.ClearContent();
            Response.ContentType = "image/png";
            Response.BinaryWrite(ms.ToArray());
            g.Dispose();
            bmp.Dispose();
            Response.End();
        }
Example #4
0
    /// <summary>
    /// Applies matrix transformation to graphics
    /// </summary>
    private static void TransformCoordinates()
    {
        using (var bitmap = new Bitmap(600, 300, PixelFormat.Format24bppRgb, RgbColor.White))
            using (var graphics = bitmap.GetAdvancedGraphics())
            {
                // Move coordinate system
                var matrix1 = new System.Drawing.Drawing2D.Matrix();
                matrix1.Translate(bitmap.Width / 2, bitmap.Height / 2);

                graphics.Transform = matrix1;

                DrawEllipseAndText(graphics, 30);

                // Move, shear and rotate coordinate system
                var matrix2 = new System.Drawing.Drawing2D.Matrix();
                matrix2.Translate(bitmap.Width / 2, bitmap.Height / 2);
                matrix2.Shear(0.5f, 0.1f);
                matrix2.Rotate(30f);

                graphics.Transform = matrix2;

                DrawEllipseAndText(graphics, 255);

                bitmap.Save("../../../../_Output/TransformCoordinates.png");
            }
    }
Example #5
0
 public Color[,] shear(Color[,] Org_Buffer, float sx, float sy)
 {
     flag_rotate_shear = true;
     Matrix M = new Matrix();
     M.Shear((float)sx, (float)sy);
     return Transform(Org_Buffer, M);
 }
        public override void Draw(CGRect rect)
        {
            Graphics g = Graphics.FromCurrentContext ();
            int offset = 20;

            // Scale:
            var m = new Matrix(1, 2, 3, 4, 0, 1);
            g.DrawString ("Original Matrix:", Font, Brushes.Black, 10, 10);
            DrawMatrix (m, g, 10, 10 + offset);
            g.DrawString ("Scale - Prepend:", Font, Brushes.Black, 10, 10 + 2 * offset);
            m.Scale (1, 0.5f, MatrixOrder.Prepend);
            DrawMatrix (m, g, 10, 10 + 3 * offset);
            g.DrawString ("Scale - Append:", Font, Brushes.Black, 10, 10 + 4 * offset);
            m = new Matrix (1, 2, 3, 4, 0, 1);
            m.Scale (1, 0.5f, MatrixOrder.Append);
            DrawMatrix (m, g, 10, 10 + 5 * offset);

            // Translation:
            m = new Matrix (1, 2, 3, 4, 0, 1);
            g.DrawString ("Translation - Prepend:", Font, Brushes.Black, 10, 10 + 6 * offset);
            m.Translate (1, 0.5f, MatrixOrder.Prepend);
            DrawMatrix (m, g, 10, 10 + 7 * offset);
            g.DrawString ("Translation - Append:", Font, Brushes.Black, 10, 10 + 8 * offset);
            // Reset m to the original matrix:
            m = new Matrix(1, 2, 3, 4, 0, 1);
            m.Translate (1, 0.5f, MatrixOrder.Append);
            DrawMatrix (m, g, 10, 10 + 9 * offset);

            m = new Matrix (1, 2, 3, 4, 0, 1);
            g.DrawString ("Rotation - Prepend:", Font, Brushes.Black, 10, 10 + 10 * offset);
            m.Rotate (45, MatrixOrder.Prepend);
            DrawMatrix (m, g, 10, 10 + 11 * offset);
            g.DrawString ("Rotation - Append:", Font, Brushes.Black, 10, 10 + 12 * offset);
            // Reset m to the original matrix:
            m = new Matrix (1, 2, 3, 4, 0, 1);
            m.Rotate (45, MatrixOrder.Append);
            DrawMatrix (m, g, 10, 10 + 13 * offset);

            // Rotation at (x = 1, y = 2):
            m = new Matrix (1, 2, 3, 4, 0, 1);
            g.DrawString ("Rotation At - Prepend:", Font, Brushes.Black, 10, 10 + 14 * offset);
            m.RotateAt (45, new Point (1, 2), MatrixOrder.Prepend);
            DrawMatrix (m, g, 10, 10 + 15 * offset);
            g.DrawString ("Rotation At - Append:", Font, Brushes.Black, 10, 10 + 16 * offset);
            m = new Matrix (1, 2, 3, 4, 0, 1);
            m.RotateAt (45, new Point (1, 2), MatrixOrder.Append);
            DrawMatrix(m, g, 10, 10 + 17 * offset);

            // Shear:
            m = new Matrix (1, 2, 3, 4, 0, 1);
            g.DrawString ("Shear - Prepend:", Font, Brushes.Black, 10, 10 + 18 * offset);
            m.Shear (1, 2, MatrixOrder.Prepend);
            DrawMatrix (m, g, 10, 10 + 19 * offset);
            g.DrawString ("Shear - Append:", Font, Brushes.Black, 10, 10 + 20 * offset);
            // Reset m to the original matrix:
            m = new Matrix (1, 2, 3, 4, 0, 1);
            m.Shear (1, 2, MatrixOrder.Append);
            DrawMatrix (m, g, 10, 10 + 21 * offset);
        }
Example #7
0
        public void full_transform(float ScX, float ScY, float ShX, float ShY, float RoAngle)
        {
            Matrix transform_matrix = new Matrix();
            transform_matrix.Scale(ScX, ScY, MatrixOrder.Append);
            transform_matrix.Shear(ShX, ShY, MatrixOrder.Append);
            transform_matrix.Rotate(RoAngle, MatrixOrder.Append);

            Transform(transform_matrix);
        }
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
        public static Image TransformImage(Image img, float theta, float shearx, float sheary, float scalex, float scaley)
        {
            var rd_theta = (float)(theta * Math.PI / 180.0);
            float cos_theta = (float)Math.Cos(rd_theta);
            float sin_theta = (float)Math.Sin(rd_theta);

            Matrix sizeMat = new Matrix();
            sizeMat.Scale(scalex, scaley);
            sizeMat.Rotate(theta);
            sizeMat.Shear(shearx, sheary);

            Point[] cornerPoints = new Point[4]
            {
                new Point(0,0),
                new Point((int)img.Width,0),
                new Point(0,(int)img.Height),
                new Point((int)img.Width,(int)img.Height)
            };

            sizeMat.TransformPoints(cornerPoints);

            var minX = Math.Min(cornerPoints[0].X,
                Math.Min(cornerPoints[1].X, Math.Min(cornerPoints[2].X, cornerPoints[3].X)));
            var maxX = Math.Max(cornerPoints[0].X,
                Math.Max(cornerPoints[1].X, Math.Max(cornerPoints[2].X, cornerPoints[3].X)));
            var minY = Math.Min(cornerPoints[0].Y,
                Math.Min(cornerPoints[1].Y, Math.Min(cornerPoints[2].Y, cornerPoints[3].Y)));
            var maxY = Math.Max(cornerPoints[0].Y,
                Math.Max(cornerPoints[1].Y, Math.Max(cornerPoints[2].Y, cornerPoints[3].Y)));

            //float fnew_width = Math.Abs(sin_theta) * img.Height + Math.Abs(cos_theta) * img.Width;
            //float fnew_height = Math.Abs(sin_theta) * img.Width + Math.Abs(cos_theta) * img.Height;

            float fnew_width = maxX - minX;
            float fnew_height = maxY - minY;

            Matrix mat = new Matrix();
            mat.Translate(fnew_width / 2, fnew_height / 2);
            mat.Scale(scalex, scaley);

            mat.Rotate(theta);
            mat.Shear(shearx, sheary);

            Image result = new Image((uint)fnew_width, (uint)fnew_height, img.Components);

            mat.Translate(-img.Width / 2, -img.Height / 2);
            float ih = img.Height;

            mat.Invert();

            PointF[] op_point = new PointF[1];

            for (uint y = 0; y < result.Height; y++)
            {
                for (uint x = 0; x < result.Width; x++)
                {
                    op_point[0] = new PointF((int)x, (int)y);
                    mat.TransformPoints(op_point);
                    float p_x = op_point[0].X;
                    float p_y = op_point[0].Y;
                    int absX = (int)op_point[0].X;
                    int absY = (int)op_point[0].Y;
                    if (p_x < img.Width - 1 && p_y < img.Height - 1 && p_x >= 0 && p_y >= 0)
                    {
                        int X1 = absX;
                        int X2 = X1 + 1;
                        int Y1 = absY;
                        int Y2 = Y1 + 1;

                        Pixel P1 = img.getPixel((uint)X1, (uint)Y1);
                        Pixel P2 = img.getPixel((uint)X2, (uint)Y1);
                        Pixel P3 = img.getPixel((uint)X1, (uint)Y2);
                        Pixel P4 = img.getPixel((uint)X2, (uint)Y2);

                        float x_frac = p_x - (float)X1;
                        float y_frac = p_y - (float)Y1;

                        float Z1R = (float)(P1.R) * (1f - x_frac) + P2.R * x_frac;
                        float Z1G = (float)(P1.G) * (1f - x_frac) + P2.G * x_frac;
                        float Z1B = (float)(P1.B) * (1f - x_frac) + P2.B * x_frac;

                        float Z2R = (float)(P3.R) * (1f - x_frac) + P4.R * x_frac;
                        float Z2G = (float)(P3.G) * (1f - x_frac) + P4.G * x_frac;
                        float Z2B = (float)(P3.B) * (1f - x_frac) + P4.B * x_frac;

                        int R = (int)(Z1R * (1f - y_frac) + Z2R * y_frac);
                        int G = (int)(Z1G * (1f - y_frac) + Z2G * y_frac);
                        int B = (int)(Z1B * (1f - y_frac) + Z2B * y_frac);

                        Color c = Color.FromArgb(R, G, B);
                        result.setPixel(x, y, new Pixel(c.R, c.G, c.B, 255));
                    }
                }
            }

            return result;
        }
Example #11
0
        public void shear(float ShearX, float ShearY, Interpolation interpol = Interpolation.Bilinear)
        {
            Matrix transform_matrix = new Matrix();
            transform_matrix.Shear(ShearX, ShearY);

            Transform(transform_matrix, interpol);
        }
Example #12
0
        public void full_transform(float ScX, float ScY, float ShX, float ShY, float RoAngle, Interpolation interpol = Interpolation.Bilinear)
        {
            Matrix transform_matrix = new Matrix();
            transform_matrix.Shear(ShX, ShY);
            transform_matrix.Rotate(RoAngle, MatrixOrder.Prepend);
            transform_matrix.Scale(ScX, ScY, MatrixOrder.Prepend);

            Transform(transform_matrix, interpol);
        }
Example #13
0
        public override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            Graphics g = e.Graphics;

            if (Bounds.Width > 0 && Bounds.Height > 0)
            {
                RenderBackground(g, Bounds);

                int dx = (int)(Bounds.Width * .2f);
                int dy = (int)(Bounds.Height * .2f);

                Rectangle r = Bounds;
                r.Inflate(-dx, -dy);

                Rectangle srcRect = new Rectangle(0, 0, _ElemWidth, _ElemHeight);
                GraphicsContainer containerState = g.BeginContainer(r, srcRect, GraphicsUnit.Pixel);

                g.SmoothingMode = SmoothingMode.AntiAlias;
                g.PixelOffsetMode = PixelOffsetMode.Default;

                if (NumIndicator.ShearFactor != 0)
                {
                    Matrix trans = new Matrix();
                    trans.Shear(NumIndicator.ShearFactor, 0.0F);

                    g.Transform = trans;
                }

                Brush brushOn = BrushOn;
                Brush brushOff = BrushOff;

                RenderSegments(g, brushOn, brushOff);
                RenderPoints(g, brushOn, brushOff);

                g.EndContainer(containerState);
            }
        }
        public override void DrawRect(System.Drawing.RectangleF dirtyRect)
        {
            Graphics g = new Graphics();
            int offset = 20;

            // Scale:
            Matrix m = new Matrix(1, 2, 3, 4, 0, 1);
            g.DrawString("Original Matrix:", this.Font,
                         Brushes.Black, 10, 10);
            DrawMatrix(m, g, 10, 10 + offset);
            g.DrawString("Scale - Prepend:", this.Font,
                         Brushes.Black, 10, 10 + 2 * offset);
            m.Scale(1, 0.5f, MatrixOrder.Prepend);
            DrawMatrix(m, g, 10, 10 + 3 * offset);
            g.DrawString("Scale - Append:", this.Font,
                         Brushes.Black, 10, 10 + 4 * offset);
            // Reset m to the original matrix:
            m = new Matrix(1, 2, 3, 4, 0, 1);
            m.Scale(1, 0.5f, MatrixOrder.Append);
            DrawMatrix(m, g, 10, 10 + 5 * offset);

            // Translation:
            m = new Matrix(1, 2, 3, 4, 0, 1);
            g.DrawString("Translation - Prepend:", this.Font,
                         Brushes.Black, 10, 10 + 6 * offset);
            m.Translate(1, 0.5f, MatrixOrder.Prepend);
            DrawMatrix(m, g, 10, 10 + 7 * offset);
            g.DrawString("Translation - Append:", this.Font,
                         Brushes.Black, 10, 10 + 8 * offset);
            // Reset m to the original matrix:
            m = new Matrix(1, 2, 3, 4, 0, 1);
            m.Translate(1, 0.5f, MatrixOrder.Append);
            DrawMatrix(m, g, 10, 10 + 9 * offset);

            // Rotation:
            m = new Matrix(1, 2, 3, 4, 0, 1);
            g.DrawString("Rotation - Prepend:", this.Font,
                         Brushes.Black, 10, 10 + 10 * offset);
            m.Rotate(45, MatrixOrder.Prepend);
            DrawMatrix(m, g, 10, 10 + 11 * offset);
            g.DrawString("Rotation - Append:", this.Font,
                         Brushes.Black, 10, 10 + 12 * offset);
            // Reset m to the original matrix:
            m = new Matrix(1, 2, 3, 4, 0, 1);
            m.Rotate(45, MatrixOrder.Append);
            DrawMatrix(m, g, 10, 10 + 13 * offset);

            // Rotation at (x = 1, y = 2):
            m = new Matrix(1, 2, 3, 4, 0, 1);
            g.DrawString("Rotation At - Prepend:", this.Font,
                         Brushes.Black, 10, 10 + 14 * offset);
            m.RotateAt(45, new PointF(1, 2), MatrixOrder.Prepend);
            DrawMatrix(m, g, 10, 10 + 15 * offset);
            g.DrawString("Rotation At - Append:", this.Font,
                         Brushes.Black, 10, 10 + 16 * offset);
            // Reset m to the original matrix:
            m = new Matrix(1, 2, 3, 4, 0, 1);
            m.RotateAt(45, new PointF(1, 2), MatrixOrder.Append);
            DrawMatrix(m, g, 10, 10 + 17 * offset);

            // Shear:
            m = new Matrix(1, 2, 3, 4, 0, 1);
            g.DrawString("Shear - Prepend:", this.Font,
                         Brushes.Black, 10, 10 + 18 * offset);
            m.Shear(1, 2, MatrixOrder.Prepend);
            DrawMatrix(m, g, 10, 10 + 19 * offset);
            g.DrawString("Shear - Append:", this.Font,
                         Brushes.Black, 10, 10 + 20 * offset);
            // Reset m to the original matrix:
            m = new Matrix(1, 2, 3, 4, 0, 1);
            m.Shear(1, 2, MatrixOrder.Append);
            DrawMatrix(m, g, 10, 10 + 21 * offset);
        }
Example #15
0
		public void Transform_Matrix()
		{
			path = new GraphicsPath ();
			path.AddLine (new Point (100, 100), new Point (200, 100));
			path.AddLine (new Point (200, 200), new Point (10, 100));

			path.StartFigure();
			path.AddBezier( 10, 10, 50, 250, 100, 5, 200, 280);
			path.StartFigure();
			path.AddRectangle (new Rectangle (10, 20, 200, 200));

			path.StartFigure();
			path.AddLine (new Point (200, 200), new Point (200, 10));

			Matrix matrix = new Matrix ();
			matrix.Scale (1.2f, 1.4f);
			matrix.Shear (0.9f, -1.15f);
			matrix.Rotate (5);

			path.Transform (matrix);

			PointF [] expectedPoints = new PointF [] {	new PointF(226.0865f, 5.313778f), 
														new PointF(355.0427f, -142.8718f), 
														new PointF(452.173f, 10.62756f), 
														new PointF(110.0259f, 138.6808f), 
														new PointF(22.60865f, 0.5313778f), 
														new PointF(307.3039f, 309.6555f), 
														new PointF(133.8127f, -140.5106f), 
														new PointF(529.8773f, 133.427f), 
														new PointF(32.32168f, 15.88131f), 
														new PointF(290.234f, -280.4898f), 
														new PointF(484.4947f, 26.50887f), 
														new PointF(226.5823f, 322.8799f), 
														new PointF(452.173f, 10.62756f), 
														new PointF(267.6254f, -281.0212f)};
			
			for(int i = 0; i < path.PointCount; i++) {
				DrawingTest.AssertAlmostEqual(expectedPoints [i], path.PathPoints [i]);
			}

			byte [] expectedTypes = new byte [] {	(byte) PathPointType.Start, 
													(byte) PathPointType.Line, 
													(byte) PathPointType.Line, 
													(byte) PathPointType.Line, 
													(byte) PathPointType.Start, 
													(byte) PathPointType.Bezier3, 
													(byte) PathPointType.Bezier3, 
													(byte) PathPointType.Bezier3, 
													(byte) PathPointType.Start, 
													(byte) PathPointType.Line, 
													(byte) PathPointType.Line, 
													(byte) (PathPointType.Line  |  PathPointType.CloseSubpath), 
													(byte) PathPointType.Start, 
													(byte) PathPointType.Line};

			for (int i=0; i < expectedTypes.Length; i++) {
				Assert.AreEqual (expectedTypes [i], path.PathTypes [i]);
			}	

			t.Graphics.DrawPath (p, path);
			t.Show ();
			//t.AssertCompare ();
		}
Example #16
0
		public void GetBounds_Matrix_Pen()
		{
			path = new GraphicsPath ();
			path.AddLine (new Point (100, 100), new Point (400, 100));
			path.AddLine (new Point (400, 200), new Point (10, 100));

			path.StartFigure ();
			path.AddBezier( 10, 10, 50, 250, 100, 5, 200, 280);
			path.StartFigure ();
			path.AddRectangle (new Rectangle (10, 20, 300, 400));

			path.StartFigure ();
			path.AddLine (new Point (400, 400), new Point (400, 10));

			Matrix matrix = new Matrix ();
			matrix.Scale (0.2f,0.3f);
			matrix.Shear (0.5f, 0.5f);

			Pen p = new Pen (Color.AliceBlue, 45);

			RectangleF actual = path.GetBounds (matrix, p);
			RectangleF expected = new RectangleF (21f, 31.2f, 2758.363f, 3046.163f);

			// we do not know exacly how the bounding rectangle 
			// is calculated so we just want to obtain bounds
			// that still contain the path widened by oen and transformed by matrix
			path.Widen (p, matrix);
			RectangleF widened = path.GetBounds ();
			Assert.IsTrue (actual.Contains (widened));

//			DrawingTest.AssertAlmostEqual(expected.X, actual.X);
//			DrawingTest.AssertAlmostEqual(expected.Y, actual.Y);
//			DrawingTest.AssertAlmostEqual(expected.Width, actual.Width);
//			DrawingTest.AssertAlmostEqual(expected.Height, actual.Height);

			path = new GraphicsPath ();
			path.AddLine (new Point (100, 100), new Point (400, 100));
			path.AddLine (new Point (400, 200), new Point (10, 100));

			path.StartFigure ();
			path.AddBezier( 10, 10, 50, 250, 100, 5, 200, 280);
			path.StartFigure ();
			path.AddRectangle (new Rectangle (10, 20, 300, 400));

			path.StartFigure ();
			path.AddLine (new Point (400, 400), new Point (400, 10));

			p = new Pen (Color.AliceBlue, 45);
			p.DashCap = DashCap.Triangle;
			p.DashStyle = DashStyle.Dash;

			actual = path.GetBounds (matrix, p);
			expected = new RectangleF (21f, 31.2f, 2758.363f, 3046.163f);

			// we do not know exacly how the bounding rectangle 
			// is calculated so we just want to obtain bounds
			// that still contain the path widened by oen and transformed by matrix
			path.Widen (p, matrix);
			widened = path.GetBounds ();
			Assert.IsTrue (actual.Contains (widened));

//			DrawingTest.AssertAlmostEqual(expected.X, actual.X);
//			DrawingTest.AssertAlmostEqual(expected.Y, actual.Y);
//			DrawingTest.AssertAlmostEqual(expected.Width, actual.Width);
//			DrawingTest.AssertAlmostEqual(expected.Height, actual.Height);

			//t.AssertCompare ();
		}
 void ProjectiveLetter()
 {
     try
     {
         Bitmap bmp = new Bitmap(300, 200);
         Graphics g = Graphics.FromImage(bmp);
         g.Clear(Color.White);
         g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;   //设置文本输出的质量
         g.SmoothingMode = SmoothingMode.AntiAlias;                  //消除绘制时出现的锯齿
         Font font = new Font("宋体", 48);
         Matrix martix = new Matrix();
         martix.Shear(-1.4F, 0.0F);                                  //设置投影
         martix.Scale(1, 0.5F);                                      //设置缩放
         martix.Translate(168, 118);                                 //设置平移
         g.Transform = martix;                                       //设置坐标平面变换
         SolidBrush wordBrush = new SolidBrush(Color.Gray);            //设置文字的画刷
         SolidBrush shadowBrush = new SolidBrush(Color.SlateBlue);       //设置投影的画刷
         string str = "Test";
         g.DrawString(str, font, wordBrush, new PointF(0, 60));
         g.ResetTransform();                                             //变换矩阵重置为单位矩阵
         g.DrawString(str, font, shadowBrush, new PointF(0, 60));
         MemoryStream ms = new MemoryStream();
         bmp.Save(ms, ImageFormat.Gif);
         Response.ClearContent();
         Response.ContentType = "image/Gif";
         Response.BinaryWrite(ms.ToArray());
     }
     catch (Exception ex)
     {
         Response.Write(ex.Message);
     }
 }
Example #18
0
		public static RotateMatrix Rotate(
			double angle
			, double centerX
			, double centerY
			, double width
			, double height
			, double scaleX
			, double scaleY
			, double shearX
			, double shearY
			, double drawOffsetX
			, double drawOffsetY
		)
		{
			float angleF = (float)angle;
			float centerXF = (float)centerX;
			float centerYF = (float)centerY;
			float widthF = (float)width;
			float heightF = (float)height;
			float scaleXF = (float)scaleX;
			float scaleYF = (float)scaleY;
			float shearXF = (float)shearX;
			float shearYF = (float)shearY;
			float drawOffsetXF = (float)drawOffsetX;
			float drawOffsetYF = (float)drawOffsetY;

			PointF offset = new PointF();
			PointF ur = new PointF();
			Matrix matrix = new Matrix();
			PointF center = new PointF(centerXF, centerYF);
			angleF = angleF % 360;
			if (angleF < 0)
			{
				angleF += 360;
			}
			if (angleF % 90 == 0)
			{
				angleF += 0.01f;
			}

			widthF = centerXF * 2 * scaleXF;
			heightF = centerYF * 2 * scaleYF;
			matrix.Scale(scaleXF, scaleYF);
			matrix.Shear(shearXF, shearYF);
			matrix.RotateAt(angleF, center);

			offset.X = matrix.OffsetX;
			offset.Y = matrix.OffsetY;
			float rs, rc;
			rs = (float)Math.Sin(angleF * Math.PI / 180);
			rc = (float)Math.Cos(angleF * Math.PI / 180);
			ur.X = rc * widthF;
			ur.Y = rs * widthF;
			ur.X += matrix.OffsetX;
			ur.Y += matrix.OffsetY;
			angleF = angleF % 360;
			if (angleF >= 0 && angleF <= 90)
			{
				offset.X = ur.X - widthF;
				offset.Y = -matrix.OffsetY;
			}
			else if (angleF > 90 && angleF < 180)
			{
				offset.X = -widthF + matrix.OffsetX;
				offset.Y = ur.Y - heightF;
			}
			else if (angleF >= 180 && angleF <= 270)
			{
				offset.X = -ur.X;
				offset.Y = matrix.OffsetY - heightF;
			}
			else
			{
				offset.X = -matrix.OffsetX;
				offset.Y = -ur.Y;
			}

			matrix.RotateAt(-angleF, center);
			matrix.Translate(offset.X / scaleXF, offset.Y / scaleYF);
			//matrix.Translate(offset.X / scaleXF + drawOffsetXF / scaleXF, offset.Y / scaleYF + drawOffsetYF / scaleYF);
			matrix.RotateAt(angleF, center);
			RotateMatrix rm = new RotateMatrix(matrix, angleF, -offset.X, -offset.Y, widthF, heightF);
			rm.AbsoluteOffset = new PointF(drawOffsetXF, drawOffsetYF);
			return rm;
		}
Example #19
0
        private void SevenSegment_Paint(object sender, PaintEventArgs e)
        {
            int useValue = customPattern;

            Brush brushLight = new SolidBrush(colorLight);
            Brush brushDark = new SolidBrush(colorDark);

            // Define transformation for our container...
            RectangleF srcRect = new RectangleF(0.0F, 0.0F, gridWidth, gridHeight);
            RectangleF destRect = new RectangleF(Padding.Left, Padding.Top, this.Width - Padding.Left - Padding.Right, this.Height - Padding.Top - Padding.Bottom);
            
            // Begin graphics container that remaps coordinates for our convenience
            GraphicsContainer containerState = e.Graphics.BeginContainer(destRect, srcRect, GraphicsUnit.Pixel);

            Matrix trans = new Matrix();
            trans.Shear(italicFactor, 0.0F);
            e.Graphics.Transform = trans;

            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
            e.Graphics.PixelOffsetMode = PixelOffsetMode.Default;

            // Draw elements based on whether the corresponding bit is high
            e.Graphics.FillPolygon((useValue & 0x1) == 0x1 ? brushLight : brushDark, segPoints[0]);
            e.Graphics.FillPolygon((useValue & 0x2) == 0x2 ? brushLight : brushDark, segPoints[1]);
            e.Graphics.FillPolygon((useValue & 0x4) == 0x4 ? brushLight : brushDark, segPoints[2]);
            e.Graphics.FillPolygon((useValue & 0x8) == 0x8 ? brushLight : brushDark, segPoints[3]);
            e.Graphics.FillPolygon((useValue & 0x10) == 0x10 ? brushLight : brushDark, segPoints[4]);
            e.Graphics.FillPolygon((useValue & 0x20) == 0x20 ? brushLight : brushDark, segPoints[5]);
            e.Graphics.FillPolygon((useValue & 0x40) == 0x40 ? brushLight : brushDark, segPoints[6]);

            if (showDot)
                e.Graphics.FillEllipse(dotOn ? brushLight : brushDark, gridWidth - 1, gridHeight - elementWidth + 1, elementWidth, elementWidth);

            e.Graphics.EndContainer(containerState);
        }
        /**
        You can use this matrix as follows:
            1 - Create new object with identity matrix (empty constructor)
            2 - Apply a set of transformations that you want to this matrix
            3 - Transform the four corners of the original image to calculate
            4 - The min X and min Y of the transformed image
            5 - The width & height of the new image buffer
            6 - Translate this matrix by (- min X, - min Y)
            7 - Invert the matrix
            8 - Use the inverted version to reverse transform all new locations in the new image buffer
        **/
        public Bitmap perform_concat_matrices_operations(bufferedLockBitmap _src_img, float _shear_x = (float)0, float _shear_y = (float)0, float _scale_x = (float)1, float _scale_y = (float)1, float _rotate_theta = (float)0)
        {
            bufferedLockBitmap ret;

            // 1 - Create new object with identity matrix (empty constructor)
            Matrix transformations_matrix = new Matrix();
            // 2 - Apply a set of transformations that you want to this matrix
            transformations_matrix.Rotate(_rotate_theta, MatrixOrder.Append);
            transformations_matrix.Scale(_scale_x, _scale_y, MatrixOrder.Append);
            transformations_matrix.Shear(_shear_x, _shear_y, MatrixOrder.Append);
            // 3 - Transform the four corners of the original image to calculate
            /**
             * To get the size of the new (destination) image,
             * apply the forward mapping to the four corners of the original image
             * ([0,0], [W-1,0], [0,H-1], [W-1,H-1])
             * to get their new locations.
             * Then use these new four locations to get the width and height of the destination image
             * (e.g. to get new width:
             * find min X & max X of the four new points and subtract them,
             * do the same for Y to get the new height)
             */
            Point[] corner_points = {
                                        new Point(0, 0),
                                        new Point(_src_img.source.Width - 1, 0),
                                        new Point(0, _src_img.source.Height - 1),
                                        new Point(_src_img.source.Width - 1, _src_img.source.Height - 1)
                                    };

            transformations_matrix.TransformPoints(corner_points);

            int min_x = find_min_x(corner_points);
            int min_y = find_min_y(corner_points);

            int max_x = find_max_x(corner_points);
            int max_y = find_max_y(corner_points);

            int new_width =Math.Abs(Math.Abs(max_x) - Math.Abs(min_x));//edited
            int new_height = Math.Abs(max_y) - Math.Abs(min_y);//edited

            // 4 - The min X and min Y of the transformed image
            /**
             * To make the transformed image totally fit inside the buffer, a translation with (- min X, - min Y) should be appended to the original transformation matrix (W) before inverting it.
             */

            // 6 - Translate this matrix by (- min X, - min Y)
            transformations_matrix.Translate(-min_x, -min_y, MatrixOrder.Append);

            // 7 - Invert the matrix
            transformations_matrix.Invert();

            // 8 - Use the inverted version to reverse transform all new locations in the new image buffer
            return apply_transformation_matrix_to_bitmap_or_buffer(transformations_matrix, _src_img, new_width, new_height).source;
        }
Example #21
0
		public void Shear ()
		{
			Matrix matrix = new Matrix (10, 20, 30, 40, 50, 60);
			matrix.Shear (2, 4);

			Assert.AreEqual (130, matrix.Elements[0], "H#1");
			Assert.AreEqual (180, matrix.Elements[1], "H#2");
			Assert.AreEqual (50, matrix.Elements[2], "H#3");
			Assert.AreEqual (80, matrix.Elements[3], "H#4");
			Assert.AreEqual (50, matrix.Elements[4], "H#5");
			Assert.AreEqual (60, matrix.Elements[5], "H#6");
			
			matrix = new Matrix (5, 3, 9, 2, 2, 1);
			matrix.Shear  (10, 20);			
			
			Assert.AreEqual (185, matrix.Elements[0], "H#7");
			Assert.AreEqual (43, matrix.Elements[1], "H#8");
			Assert.AreEqual (59, matrix.Elements[2], "H#9");
			Assert.AreEqual (32, matrix.Elements[3], "H#10");
			Assert.AreEqual (2, matrix.Elements[4], "H#11");
			Assert.AreEqual (1, matrix.Elements[5], "H#12");
		}
Example #22
0
        /// <summary>
        /// 生产图片验证码
        /// </summary>
        /// <returns></returns>
        public static Bitmap NextImage(int width = 70, int height = 34, int length = 4)
        {
            //获取随机字符
            Random rand = new Random();
            string str = RandomString(length);
            HttpContext.Current.Session["verificationCode"] = str;

            //创建画板
            Bitmap image = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(image);
            //g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.InterpolationMode = InterpolationMode.Low;
            //g.CompositingMode = CompositingMode.SourceOver;
            //g.CompositingQuality = CompositingQuality.HighQuality;
            g.CompositingQuality = CompositingQuality.HighSpeed;
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
            g.SmoothingMode = SmoothingMode.AntiAlias;

            //绘制渐变背景
            Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);
            Brush brushBack = new LinearGradientBrush(rect, Color.FromArgb(rand.Next(150, 256), 255, 255), Color.FromArgb(255, rand.Next(150, 256), 255), rand.Next(90));
            g.FillRectangle(brushBack, rect);

            //绘制干扰曲线
            for (int i = 0; i < 2; i++)
            {
                Point p1 = new Point(0, rand.Next(image.Height));
                Point p2 = new Point(rand.Next(image.Width), rand.Next(image.Height));
                Point p3 = new Point(rand.Next(image.Width), rand.Next(image.Height));
                Point p4 = new Point(image.Width, rand.Next(image.Height));
                Point[] p = { p1, p2, p3, p4 };
                Pen pen = new Pen(Color.Gray, 1);
                g.DrawBeziers(pen, p);
            }

            //逐个绘制文字
            for (int i = 0; i < str.Length; i++)
            {
                string strChar = str.Substring(i, 1);
                int deg = rand.Next(-15, 15);
                float x = (image.Width / str.Length / 2) + (image.Width / str.Length) * i;
                float y = image.Height / 2;
                //随机字体大小
                Font font = new Font("Consolas", rand.Next(16, 24), FontStyle.Regular);
                SizeF size = g.MeasureString(strChar, font);
                Matrix m = new Matrix();
                //旋转
                m.RotateAt(deg, new PointF(x, y), MatrixOrder.Append);
                //扭曲
                m.Shear(rand.Next(-10, 10) * 0.03f, 0);
                g.Transform = m;
                //随机渐变画笔
                Brush brushPen = new LinearGradientBrush(rect, Color.FromArgb(rand.Next(0, 256), 0, 0), Color.FromArgb(0, 0, rand.Next(0, 256)), rand.Next(90));
                g.DrawString(str.Substring(i, 1), font, brushPen, new PointF(x - size.Width / 2, y - size.Height / 2));

                g.Transform = new Matrix();
            }

            g.Save();
            g.Dispose();

            return image;
        }
Example #23
0
        public static Color[,] Shear(Color[,] sourceBuffer, int oWidth, int oHeight)
        {
            Color[,] Buff;
               Buff = sourceBuffer;
               Matrix TrsMat = new Matrix();
               TrsMat.Shear(1, 0);

               Point[] mypoint = new Point[1];
               mypoint[0].X = 0;
               mypoint[0].Y = 0;
               TrsMat.TransformPoints(mypoint);
               int X0 = mypoint[0].X;
               int Y0 = mypoint[0].Y;
               mypoint[0].X = oWidth;
               mypoint[0].Y = 0;
               TrsMat.TransformPoints(mypoint);
               int X1 = mypoint[0].X;
               int Y1 = mypoint[0].Y;
               mypoint[0].X = 0;
               mypoint[0].Y = oHeight;
               TrsMat.TransformPoints(mypoint);
               int X2 = mypoint[0].X;
               int Y2 = mypoint[0].Y;
               mypoint[0].X = oWidth;
               mypoint[0].Y = oHeight;
               TrsMat.TransformPoints(mypoint);
               int X3 = mypoint[0].X;
               int Y3 = mypoint[0].Y;

               int MinX = Math.Min(X0, X1);
               MinX = Math.Min(MinX, X2);
               MinX = Math.Min(MinX, X3);

               int MinY = Math.Min(Y0, Y1);
               MinY = Math.Min(MinY, Y2);
               MinY = Math.Min(MinY, Y3);

               int MaxX = Math.Max(X0, X1);
               MaxX = Math.Max(MaxX, X2);
               MaxX = Math.Max(MaxX, X3);

               int MaxY = Math.Max(Y0, Y1);
               MaxY = Math.Max(MaxY, Y2);
               MaxY = Math.Max(MaxY, Y3);

               int nWidth = MaxX - MinX;
               int nHeight = MaxY - MinY;
               TrsMat.Translate(-MinX, -MinY);
               TrsMat.Invert();
               Buff = new Color[nWidth, nHeight];

               for (int i = 0; i < nHeight; i++)
               {
               for (int j = 0; j < nWidth; j++)
               {
                   mypoint[0].X = j;
                   mypoint[0].Y = i;
                   TrsMat.TransformPoints(mypoint);
                   if (mypoint[0].X < oWidth && mypoint[0].X >= 0 && mypoint[0].Y < oHeight && mypoint[0].Y >= 0)
                   {
                       Buff[j, i] = sourceBuffer[mypoint[0].X, mypoint[0].Y];
                   }
                   else
                   {
                       Buff[j, i] = Color.FromArgb(0);
                   }

               }
               }

               return Buff;
        }
        /// <summary>
        /// Create Validation Code Image
        /// </summary>
        private byte[] CreateImage(string str_ValidateCode)
        {
            int int_ImageWidth = str_ValidateCode.Length * 22;
            Random newRandom = new Random();

            Bitmap theBitmap = new Bitmap(int_ImageWidth + 6, 38);
            Graphics theGraphics = Graphics.FromImage(theBitmap);

            theGraphics.Clear(Color.White);

            drawLine(theGraphics, theBitmap, newRandom);
            theGraphics.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, theBitmap.Width - 1, theBitmap.Height - 1);

            for (int int_index = 0; int_index < str_ValidateCode.Length; int_index++)
            {
                Matrix X = new Matrix();
                X.Shear((float)newRandom.Next(0, 300) / 1000 - 0.25f, (float)newRandom.Next(0, 100) / 1000 - 0.05f);
                theGraphics.Transform = X;
                string str_char = str_ValidateCode.Substring(int_index, 1);
                System.Drawing.Drawing2D.LinearGradientBrush newBrush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, theBitmap.Width, theBitmap.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                Point thePos = new Point(int_index * 21 + 1 + newRandom.Next(3), 1 + newRandom.Next(13));

                Font theFont = new Font(Fonts[newRandom.Next(Fonts.Length - 1)], newRandom.Next(14, 18), FontStyle.Bold);

                theGraphics.DrawString(str_char, theFont, newBrush, thePos);
            }

            drawPoint(theBitmap, newRandom);

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

            var ret = ms.ToArray();
            theGraphics.Dispose();
            theBitmap.Dispose();
            ms.Close();
            return ret;
        }
        private void generateImage()
        {
            if (!isDirty) return;
            // Create a new 32-bit bitmap image.
            Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);

            // Create a graphics object for drawing.
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                g.SmoothingMode = SmoothingMode.AntiAlias;
                Rectangle rect = new Rectangle(0, 0, width, height);

                // Fill in the background.
                HatchBrush hatchBrush = new HatchBrush(HatchStyle.SmallConfetti, backgroundDark, backgroundLight);
                g.FillRectangle(hatchBrush, rect);

                // Set up the text font.
                SizeF size;
                float fontSize = rect.Height + 1;
                Font font;
                // Adjust the font size until the text fits within the image.
                do
                {
                    fontSize--;
                    font = new Font(familyName, fontSize, fontStyle);
                    size = g.MeasureString(text, font);
                } while (size.Width > rect.Width);

                // Set up the text format.
                StringFormat format = new StringFormat();
                format.Alignment = StringAlignment.Center;
                format.LineAlignment = StringAlignment.Center;

                // Create a path using the text and warp it randomly.
                GraphicsPath path = new GraphicsPath();
                path.AddString(text, font.FontFamily, (int) font.Style, font.Size, rect, format);
                Matrix matrix = new Matrix();
                matrix.Translate(0F, 0F);
                if (System.Environment.OSVersion.Platform != PlatformID.Unix)
                {
                    float v = 4F;
                    PointF[] points =
                    {
                        new PointF(random.Next(rect.Width)/v, random.Next(rect.Height)/v),
                        new PointF(rect.Width - random.Next(rect.Width)/v, random.Next(rect.Height)/v),
                        new PointF(random.Next(rect.Width)/v, rect.Height - random.Next(rect.Height)/v),
                        new PointF(rect.Width - random.Next(rect.Width)/v, rect.Height - random.Next(rect.Height)/v)
                    };
                    path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);
                }
                else
                {
                    float xtr = (rect.Size.Width - size.Width)/2F+size.Width/10F;
                    float ytr = (rect.Size.Height - size.Height)/2F;
                    matrix.Rotate((float)random.NextDouble()*10F-5F);
                    matrix.Shear((float)random.NextDouble()*1F-0.5F,0F);
                    matrix.Translate(xtr,ytr);
                    path.Transform(matrix);
                }
                // Draw the text.
                using (hatchBrush = new HatchBrush(HatchStyle.LargeConfetti, foregroundLight, foregroundDark))
                {
                    g.FillPath(hatchBrush, path);

                    // Add some random noise.
                    int m = Math.Max(rect.Width, rect.Height);
                    for (int i = 0; i < (int) (rect.Width*rect.Height/30F); i++)
                    {
                        int x = random.Next(rect.Width);
                        int y = random.Next(rect.Height);
                        int w = random.Next(m/50);
                        int h = random.Next(m/50);
                        g.FillEllipse(hatchBrush, x, y, w, h);
                    }
                }
                // Clean up.
                font.Dispose();
            }

            // Set the image.
            image = bitmap;

            isDirty = false;
        }
Example #26
0
        private void Render(IGraphics ig)
        {
            string s = cbWhat.Text;

            if (s == "Clipping")
            {
                Pen pn = new Pen(Color.LightGray, 5);
                Pen pn2 = new Pen(Color.Yellow);

                ig.Clear(Color.Black);

                GraphicsContainer cnt = ig.BeginContainer();

                ig.SmoothingMode = SmoothingMode.HighQuality;

                ig.SetClip(new Rectangle(35,35,120,120));

                ig.DrawRectangle(pn, 5,5,45,70);
                ig.DrawRectangle(pn, 15,25,90,120);
                ig.DrawRectangle(pn, 50,30,100,170);
                ig.DrawRectangle(pn, 5,80,180,30);
                ig.DrawRectangle(pn, 75,10,40,160);

                ig.EndContainer(cnt);

                ig.DrawRectangle(pn2, 5,5,45,70);
                ig.DrawRectangle(pn2, 15,25,90,120);
                ig.DrawRectangle(pn2, 50,30,100,170);
                ig.DrawRectangle(pn2, 5,80,180,30);
                ig.DrawRectangle(pn2, 75,10,40,160);
            }
            else if (s == "Transforms")
            {

                ig.Clear(Color.Black);

                ig.RotateTransform(15);
                ig.DrawRectangle(new Pen(Color.Red,2), 260,80,50,40);
                ig.ResetTransform();
                ig.DrawRectangle(new Pen(Color.Red,2), 260,80,50,40);

                ig.TranslateTransform(15,-5);

                GraphicsContainer cnt = ig.BeginContainer();

                    ig.SmoothingMode = SmoothingMode.HighQuality;

                    ig.RotateTransform(5);
                    ig.FillEllipse(new SolidBrush(Color.Orange), 100,100,80,40);
                    ig.DrawRectangle(new Pen(Color.Orange,2), 60,80,40,40);

                    GraphicsContainer cnt2  = ig.BeginContainer();

                        ig.SmoothingMode = SmoothingMode.None;

                        ig.RotateTransform(5);
                        ig.ScaleTransform(1.1f, 1.2f);

                        ig.FillEllipse(new SolidBrush(Color.YellowGreen), 130,180,80,40);
                        ig.DrawRectangle(new Pen(Color.YellowGreen,2), 62,80,40,40);

                        GraphicsContainer cnt3  = ig.BeginContainer();

                            ig.SmoothingMode = SmoothingMode.HighQuality;

                            Matrix mm = new Matrix();
                            mm.Shear(0.3f, 0f);
                            ig.Transform = mm;

                            ig.FillEllipse(new SolidBrush(Color.Green), 180,120,80,40);
                            ig.DrawRectangle(new Pen(Color.Green,2), 62,84,40,40);

                        ig.EndContainer(cnt3);

                    ig.EndContainer(cnt2);

                    ig.FillEllipse(new SolidBrush(Color.Blue), 120,150,80,40);
                    ig.DrawRectangle(new Pen(Color.Blue,2), 64,80,40,40);

                ig.EndContainer(cnt);

                ig.FillEllipse(new SolidBrush(Color.Indigo), 80,210,80,40);
                ig.DrawRectangle(new Pen(Color.Indigo,2), 66,80,40,40);

                ig.DrawRectangle(new Pen(Color.White,2), 270,30,50,40);
                ig.ResetTransform();
                ig.DrawRectangle(new Pen(Color.White,2), 270,30,50,40);

            }
            else if (s == "Lines")
            {
                ig.SmoothingMode = SmoothingMode.AntiAlias;

                Pen ow = new Pen(Color.Purple, 12);
                ow.EndCap = LineCap.Round;
                ow.StartCap = LineCap.Round;
                ow.MiterLimit = 6f;
                ow.LineJoin = LineJoin.Miter;

                ig.SmoothingMode = SmoothingMode.None;

                Pen tp = new Pen(Color.Red, 2);
                tp.DashStyle = DashStyle.DashDot;

                ig.DrawLine(tp, 70,20,190,20);

                tp.DashStyle = DashStyle.Dash;

                ig.DrawLine(tp, 70,30,190,30);

                tp.DashStyle = DashStyle.Custom;
                tp.DashPattern = new float[] {1,8,2,2};

                ig.DrawLine(tp, 70,40,190,40);

                ig.SmoothingMode = SmoothingMode.AntiAlias;

                PointF[] pts = new PointF[4];
                pts[0] = new PointF(20,50);
                pts[1] = new PointF(30,90);
                pts[2] = new PointF(65,60);
                pts[3] = new PointF(50,40);
                ig.DrawLines(ow, pts);

                Point[] polly = new Point[]
                {
                new Point(200, 40),
                new Point(220, 140),
                new Point(240, 100),
                new Point(290, 70),
                new Point(230, 10)
                };

                ig.DrawPolygon(tp, polly);

                //arrows
                Pen arr = new Pen(Color.DarkGoldenrod, 5);
                AdjustableArrowCap aac = new AdjustableArrowCap(5,3, false);
                arr.EndCap = LineCap.Custom;
                arr.CustomEndCap = aac;
                arr.StartCap = LineCap.ArrowAnchor;
                ig.DrawLine(arr, 50,120, 150,200);

                arr.Width = 7f;
                arr.EndCap = LineCap.RoundAnchor;
                arr.StartCap = LineCap.SquareAnchor;
                ig.DrawLine(arr, 100,120, 200,200);

                arr.Width = 9;
                arr.EndCap = LineCap.DiamondAnchor;
                arr.StartCap = LineCap.ArrowAnchor;
                ig.DrawLine(arr, 150,120, 250,200);

                Point[] al = new Point[]
                {
                    new Point(200, 100),
                    new Point(300, 200),
                    new Point(300, 150)
                };

                arr.EndCap = LineCap.DiamondAnchor;
                arr.StartCap = LineCap.DiamondAnchor;
                ig.DrawLines(arr, al);

            }
            else if (s == "Curves")
            {

                PointF[] bezzie = new PointF[]
            {
                new PointF(20, 150),

                new PointF(110, 190),
                new PointF(120, 200),
                new PointF(50, 220),

                new PointF(60, 200),
                new PointF(140, 180),
                new PointF(100, 160),

                new PointF(180, 260),
                new PointF(200, 210),
                new PointF(190, 210)
            };

                Pen bpn = new Pen(Color.MediumSeaGreen, 2);
                bpn.DashStyle = DashStyle.Custom;
                bpn.DashPattern = new float[]{6,1,5,2,4,3,3,4,2,5,6,1};
                ig.DrawBeziers(bpn, bezzie);

                PointF[] curvy = new PointF[]
            {
                new PointF(130, 40),
                new PointF(70, 70),
                new PointF(50, 20),
                new PointF(120, 120),
                new PointF(150, 80),
                new PointF(80, 150),
                new PointF(80, 110)
            };

                ig.DrawCurve(new Pen(Color.Blue, 5), curvy);
                ig.DrawCurve(new Pen(Color.Red, 2), curvy, 2, 3);
                ig.DrawCurve(new Pen(Color.Yellow, 1), curvy, 1f);

                Point[] ccurvy = new Point[]
            {
                new Point(280, 30),
                new Point(260, 60),
                new Point(200, 20),
                new Point(290, 120),
                new Point(290, 80),
                new Point(230, 150),
                new Point(150, 50)
            };
                ig.DrawClosedCurve(new Pen(Color.Green, 3), ccurvy, 1f, FillMode.Alternate);
                ig.DrawClosedCurve(new Pen(Color.Purple, 1), ccurvy, 0f, FillMode.Alternate);

                Point[] fcc = new Point[]
            {
                new Point(160, 350),
                new Point(190, 370),
                new Point(130, 390),
                new Point(190, 400),
                new Point(195, 410),
                new Point(100, 430),
                new Point(160, 450)
            };
                ig.FillClosedCurve(new SolidBrush(Color.Red), fcc, FillMode.Winding, 1f);
                ig.FillClosedCurve(new SolidBrush(Color.Aquamarine), fcc, FillMode.Alternate, .2f);

            }
            else if (s == "Transparency")
            {
                Point[] fillpoly = new Point[]
                {
                    new Point(20, 130),
                    new Point(60, 90),
                    new Point(30, 20),
                    new Point(80, 20),
                    new Point(15, 90),
                    new Point(100, 50),
                    new Point(0, 50)
                };

                Color col = Color.FromArgb(96,255,0,0);

                ig.FillEllipse(new SolidBrush(Color.Ivory), 60, 140, 60, 30);
                ig.FillPolygon(new SolidBrush(Color.Ivory), fillpoly, FillMode.Winding);

                ig.TranslateTransform(10,10);
                ig.FillEllipse(new SolidBrush(col), 60, 140, 60, 30);
                ig.FillPolygon(new SolidBrush(col), fillpoly, FillMode.Alternate);
                ig.ResetTransform();

                ig.FillPie(new SolidBrush(Color.FromArgb(100,255,0,0)), 10, 200, 200, 80, 315, 90);
                ig.FillPie(new SolidBrush(Color.FromArgb(100,128,128,0)), 10, 200, 200, 80, 250, -90);
                ig.FillPie(new SolidBrush(Color.FromArgb(100,128,0,128)), 15, 205, 190, 70, 180, 270);
                ig.FillPie(new SolidBrush(Color.FromArgb(100,200,60,60)), 20, 210, 180, 60, 45, -270);

            }
            else if (s == "Fills")
            {

                LinearGradientBrush gbr1 = new LinearGradientBrush(new Point(0,0), new Point(30,20), Color.Blue, Color.Plum);

                ColorBlend blend = new ColorBlend(3);
                blend.Colors =  new Color[] {Color.Red, Color.Yellow, Color.MediumSlateBlue};
                blend.Positions = new float[] {0, .3f, 1f};
                gbr1.InterpolationColors = blend;

                Point[] sp = new Point[]
                {
                    new Point(145, 145),
                    new Point(305, 250),
                    new Point(220, 250),
                    new Point(180, 250)
                };
                ig.FillPolygon(gbr1, sp);

                LinearGradientBrush gbr2 = new LinearGradientBrush(new Point(0,0), new Point(10,20), Color.WhiteSmoke, Color.CornflowerBlue);
                gbr2.WrapMode = WrapMode.TileFlipXY;
                Point[] sp2 = new Point[]
                {
                    new Point(25, 205),
                    new Point(75, 150),
                    new Point(110, 110),
                    new Point(40, 80)
                };
                ig.FillPolygon(gbr2, sp2);

                ig.FillRectangle(new HatchBrush(HatchStyle.DiagonalBrick, Color.Khaki, Color.Peru), 000,5,20,20);
                ig.FillRectangle(new HatchBrush(HatchStyle.Vertical, Color.Bisque, Color.Peru), 020,5,20,20);
                ig.FillRectangle(new HatchBrush(HatchStyle.DarkVertical, Color.Tan, Color.Peru), 040,5,20,20);
                ig.FillRectangle(new HatchBrush(HatchStyle.DiagonalCross, Color.Chocolate, Color.Peru), 060,5,20,20);
                ig.FillRectangle(new HatchBrush(HatchStyle.WideDownwardDiagonal, Color.BurlyWood, Color.Peru), 080,5,20,20);
                ig.FillRectangle(new HatchBrush(HatchStyle.LargeConfetti, Color.Wheat, Color.Peru), 100,5,20,20);
                ig.FillRectangle(new HatchBrush(HatchStyle.ZigZag, Color.SaddleBrown, Color.Peru), 120,5,20,20);
                ig.FillRectangle(new HatchBrush(HatchStyle.HorizontalBrick, Color.Linen, Color.Peru), 140,5,20,20);
                ig.FillRectangle(new HatchBrush(HatchStyle.LightHorizontal, Color.Maroon, Color.Peru), 160,5,20,20);

                ig.FillRectangle(new HatchBrush(HatchStyle.Percent05, Color.CornflowerBlue, Color.LemonChiffon), 000,30,20,20);
                ig.FillRectangle(new HatchBrush(HatchStyle.Percent10, Color.CornflowerBlue, Color.LemonChiffon), 020,30,20,20);
                ig.FillRectangle(new HatchBrush(HatchStyle.Percent20, Color.CornflowerBlue, Color.LemonChiffon), 040,30,20,20);
                ig.FillRectangle(new HatchBrush(HatchStyle.Percent25, Color.CornflowerBlue, Color.LemonChiffon), 060,30,20,20);
                ig.FillRectangle(new HatchBrush(HatchStyle.Percent30, Color.CornflowerBlue, Color.LemonChiffon), 080,30,20,20);
                ig.FillRectangle(new HatchBrush(HatchStyle.Percent40, Color.CornflowerBlue, Color.LemonChiffon), 100,30,20,20);
                ig.FillRectangle(new HatchBrush(HatchStyle.Percent50, Color.CornflowerBlue, Color.LemonChiffon), 120,30,20,20);
                ig.FillRectangle(new HatchBrush(HatchStyle.Percent60, Color.CornflowerBlue, Color.LemonChiffon), 140,30,20,20);
                ig.FillRectangle(new HatchBrush(HatchStyle.Percent70, Color.CornflowerBlue, Color.LemonChiffon), 160,30,20,20);
                ig.FillRectangle(new HatchBrush(HatchStyle.Percent75, Color.CornflowerBlue, Color.LemonChiffon), 180,30,20,20);
                ig.FillRectangle(new HatchBrush(HatchStyle.Percent80, Color.CornflowerBlue, Color.LemonChiffon), 200,30,20,20);
                ig.FillRectangle(new HatchBrush(HatchStyle.Percent90, Color.CornflowerBlue, Color.LemonChiffon), 220,30,20,20);

            }
            else if (s == "Arcs/Pies")
            {
                //GDI does not seem to draw arcs correctly except when the ellipse is a circle.
                //These arcs demonstrate the problem.  SVGGraphics calculates arcs correctly.
                ig.DrawArc(new Pen(Color.Black, 2), 120+5*3, 120, 110*3, 110, 0, 240);
                ig.DrawArc(new Pen(Color.Black, 2), 120+10*3, 125, 100*3, 100, 0, 210);
                ig.DrawArc(new Pen(Color.Black, 2), 120+15*3, 130, 90*3, 90, 0, 180);
                ig.DrawArc(new Pen(Color.Black, 2), 120+20*3, 135, 80*3, 80, 0, 150);
                ig.DrawArc(new Pen(Color.Black, 2), 120+25*3, 140, 70*3, 70, 0, 120);
                ig.DrawArc(new Pen(Color.Black, 2), 120+30*3, 145, 60*3, 60, 0, 90);
                ig.DrawArc(new Pen(Color.Black, 2), 120+35*3, 150, 50*3, 50, 0, 60);
                ig.DrawArc(new Pen(Color.Black, 2), 120+40*3, 155, 40*3, 40, 0, 270);

                ig.DrawPie(new Pen(Color.Pink, 2), 110, 50, 100, 100, 315, 90);
                ig.DrawPie(new Pen(Color.Purple, 2), 110, 50, 100, 100, 250, -90);
                ig.DrawPie(new Pen(Color.DarkRed, 2), 115, 55, 90, 90, 180, 270);
                ig.DrawPie(new Pen(Color.Red, 2), 120, 60, 80, 80, 45, -270);

            }
            else if (s == "Text")
            {

                Font fnt1 = new Font("Helvetica", 12, FontStyle.Italic | FontStyle.Bold);
                Font fnt2 = new Font(FontFamily.GenericMonospace, 16, FontStyle.Bold);
                Font fnt3 = new Font("", 40, FontStyle.Underline);

                Rectangle rc1 = new Rectangle(30, 30, 220,20);
                StringFormat fmt1= new StringFormat();
                fmt1.Alignment = StringAlignment.Near;

                ig.DrawRectangle(new Pen(Color.Blue),  rc1);
                ig.DrawString("Text...1", fnt1, new SolidBrush(Color.DarkGreen), rc1, fmt1);

                Rectangle rc2 = new Rectangle(0,0, 120,20);
                StringFormat fmt2= new StringFormat();
                fmt2.Alignment = StringAlignment.Center;

                ig.TranslateTransform(30,160);
                ig.RotateTransform(90);

                ig.DrawRectangle(new Pen(Color.Blue),  rc2);
                ig.DrawString("Text...2", fnt2, new SolidBrush(Color.DarkGreen), rc2, fmt2);

                ig.ResetTransform();

                Rectangle rc3 = new Rectangle(30, 90, 300,30);
                StringFormat fmt3= new StringFormat();
                fmt3.Alignment = StringAlignment.Far;

                ig.DrawRectangle(new Pen(Color.Blue),  rc3);
                ig.DrawString("Text...3", fnt3, new SolidBrush(Color.DarkGreen), rc3, fmt3);

                //measurestring
                string mme = "MeasureString Is Impossible To Emulate";
                SizeF siz = ig.MeasureString(mme, fnt1);
                ig.DrawRectangle(new Pen(Color.Red), 20, 200, siz.Width, siz.Height);
                siz = ig.MeasureString(mme, fnt1, 150);
                ig.DrawRectangle(new Pen(Color.Orange), 20, 230, siz.Width, siz.Height);
                siz = ig.MeasureString(mme, fnt1,  new SizeF(150, 150), new StringFormat(StringFormatFlags.DirectionVertical));
                ig.DrawRectangle(new Pen(Color.Yellow), 20, 200, siz.Width, siz.Height);

            }
            else if (s == "Images")
            {

                Icon ike = new Icon(GetType(), "App.ico");
                ig.DrawIcon(ike, 10,10);
                //ig.DrawIcon(ike, new Rectangle(270, 400, 30, 40));

                Bitmap bmp = new Bitmap(GetType(), "test.bmp");
                ig.DrawImage(bmp, 100f, 150f);
                GraphicsContainer cnt = ig.BeginContainer();
                ig.RotateTransform(5);
                ig.DrawImage(bmp, 160f, 50f, 120f, 70f);
                ig.EndContainer(cnt);
                //ig.DrawImageUnscaled(bmp, 270, 450, 20, 20);

            }
            else
            {

            }
        }
Example #27
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 #28
0
		public void Paint(Graphics g, IPaintContext paintContext, bool bForPreview)
		{
			//_isStructureInSync = false;
			_isMeasureInSync = false;  // Change: interpret text every time in order to update plot items and \ID

			if (!this._isStructureInSync)
			{
				// this.Interpret(g);
				this.InterpretText();

				_isStructureInSync = true;
				_isMeasureInSync = false;
			}

			using (FontCache fontCache = new FontCache())
			{
				if (!this._isMeasureInSync)
				{
					// this.MeasureStructure(g, obj);
					this.MeasureGlyphs(g, fontCache, paintContext);

					MeasureBackground(g, _rootNode.Width, _rootNode.Height);

					_isMeasureInSync = true;
				}

				_cachedSymbolPositions.Clear();

				System.Drawing.Drawing2D.GraphicsState gs = g.Save();
				g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

				var bounds = Bounds;

				Matrix transformmatrix = new Matrix();
				transformmatrix.Translate((float)_location.AbsolutePivotPositionX, (float)_location.AbsolutePivotPositionY);
				transformmatrix.Rotate((float)(-Rotation));
				transformmatrix.Shear((float)Shear, 0);
				transformmatrix.Scale((float)ScaleX, (float)ScaleY);
				transformmatrix.Translate((float)bounds.X, (float)bounds.Y);

				if (!bForPreview)
				{
					TransformGraphics(g);
					g.TranslateTransform((float)bounds.X, (float)bounds.Y);
				}

				// first of all paint the background
				PaintBackground(g);

				DrawContext dc = new DrawContext();
				dc.FontCache = fontCache;
				dc.bForPreview = bForPreview;
				dc.LinkedObject = Altaxo.Main.AbsoluteDocumentPath.GetRootNodeImplementing<HostLayer>(this);
				dc.transformMatrix = transformmatrix;
				dc._cachedSymbolPositions = _cachedSymbolPositions;
				DrawGlyphs(g, dc, _cachedTextOffset.X, _cachedTextOffset.Y);
				g.Restore(gs);
			}
		}
        /**
        You can use this matrix as follows:
            1 - Create new object with identity matrix (empty constructor)
            2 - Apply a set of transformations that you want to this matrix
            3 - Transform the four corners of the original image to calculate
            4 - The min X and min Y of the transformed image
            5 - The width & height of the new image buffer
            6 - Translate this matrix by (- min X, - min Y)
            7 - Invert the matrix
            8 - Use the inverted version to reverse transform all new locations in the new image buffer
        **/
        public BufferedImage perform_concat_matrices_operations(BufferedImage _src_img, TextBox _console, float _shear_x = (float)0, float _shear_y = (float)0, float _scale_x = (float)1, float _scale_y = (float)1, float _rotate_theta = (float)0)
        {
            BufferedImage ret;
            // 1 - Create new object with identity matrix (empty constructor)
            Matrix transformations_matrix = new Matrix();
            // 2 - Apply a set of transformations that you want to this matrix
            transformations_matrix.Rotate(_rotate_theta);
            transformations_matrix.Scale(_scale_x, _scale_y);
            transformations_matrix.Shear(_shear_x, _shear_y);
            // 3 - Transform the four corners of the original image to calculate
            /**
             * To get the size of the new (destination) image,
             * apply the forward mapping to the four corners of the original image
             * ([0,0], [W-1,0], [0,H-1], [W-1,H-1])
             * to get their new locations.
             * Then use these new four locations to get the width and height of the destination image
             * (e.g. to get new width:
             * find min X & max X of the four new points and subtract them,
             * do the same for Y to get the new height)
             */
            Point[] corner_points = {
                                        new Point(0, 0),
                                        new Point(_src_img.width - 1, 0),
                                        new Point(0, _src_img.height - 1),
                                        new Point(_src_img.width - 1, _src_img.height - 1)
                                    };

            transformations_matrix.TransformPoints(corner_points);

            int min_x = find_min_x(corner_points);
            int min_y = find_min_y(corner_points);

            int max_x = find_max_x(corner_points);
            int max_y = find_max_y(corner_points);

            int new_width = max_x - min_x;
            int new_height = max_y - min_y;

            _console.Text += "Min X = ";
            _console.Text += min_x;
            _console.Text += Environment.NewLine;

            _console.Text += "Min Y = ";
            _console.Text += min_y;
            _console.Text += Environment.NewLine;

            _console.Text += "Max X = ";
            _console.Text += max_x;
            _console.Text += Environment.NewLine;

            _console.Text += "Max Y = ";
            _console.Text += max_y;
            _console.Text += Environment.NewLine;

            _console.Text += "New Width = ";
            _console.Text += new_width;
            _console.Text += Environment.NewLine;

            _console.Text += "New Height = ";
            _console.Text += new_height;
            _console.Text += Environment.NewLine;

            // 4 - The min X and min Y of the transformed image
            /**
             * To make the transformed image totally fit inside the buffer, a translation with (- min X, - min Y) should be appended to the original transformation matrix (W) before inverting it.
             */

            // 6 - Translate this matrix by (- min X, - min Y)
            transformations_matrix.Translate(-min_x, -min_y);

            // 7 - Invert the matrix
            transformations_matrix.Invert();

            // 8 - Use the inverted version to reverse transform all new locations in the new image buffer
            ret = apply_transformation_matrix_to_bitmap_or_buffer(transformations_matrix, _src_img, new_width, new_height, _console);
            return ret;
        }
        /// <summary>
        /// Create cache
        /// </summary>
        /// <param name="rectBound">The bound rectangle</param>
        /// <param name="bevelRate">Bevel rate</param>
        /// <param name="segmentWidth">Width of the segment</param>
        /// <param name="segmentInterval">Interval between segments</param>
        private void CreateCache(Rectangle rectBound, float bevelRate, float segmentWidth, float segmentInterval)
        {
            Matrix mx = new Matrix(1, 0, 0, 1, 0, 0);
            mx.Shear(-0.1f, 0);
            PointF[] pathPointCollection = new PointF[6];
            PointF[] pathDotCollection = new PointF[4];
            for(int i = 0; i < 8; ++i)
            {
                if(m_CachedPaths[i] == null)
                    m_CachedPaths[i] = new GraphicsPath();
            }
            // top '-'
            pathPointCollection[0].X = segmentWidth * bevelRate + segmentInterval;
            pathPointCollection[0].Y = segmentWidth * bevelRate;
            pathPointCollection[1].X = segmentInterval + segmentWidth * bevelRate * 2;
            pathPointCollection[1].Y = 0;
            pathPointCollection[2].X = rectBound.Width - segmentInterval - segmentWidth * bevelRate * 2;
            pathPointCollection[2].Y = 0;
            pathPointCollection[3].X = rectBound.Width - segmentInterval - segmentWidth * bevelRate;
            pathPointCollection[3].Y = segmentWidth * bevelRate;
            pathPointCollection[4].X = rectBound.Width - segmentInterval - segmentWidth;
            pathPointCollection[4].Y = segmentWidth;
            pathPointCollection[5].X = segmentWidth + segmentInterval;
            pathPointCollection[5].Y = segmentWidth;
            m_CachedPaths[0].AddPolygon(pathPointCollection);
            m_CachedPaths[0].CloseFigure();
            if (UseItalicStyle) m_CachedPaths[0].Transform(mx);

            // upper right '|'
            pathPointCollection[0].X = rectBound.Width - segmentWidth;
            pathPointCollection[0].Y = segmentWidth + segmentInterval;
            pathPointCollection[1].X = rectBound.Width - segmentWidth * bevelRate;
            pathPointCollection[1].Y = segmentWidth * bevelRate + segmentInterval;
            pathPointCollection[2].X = rectBound.Width + 1;
            pathPointCollection[2].Y = segmentWidth * bevelRate * 2 + segmentInterval + 1;
            pathPointCollection[3].X = rectBound.Width + 1;
            pathPointCollection[3].Y = (rectBound.Height >> 1) - segmentWidth * 0.5f - segmentInterval - 1;
            pathPointCollection[4].X = rectBound.Width - segmentWidth * 0.5f;
            pathPointCollection[4].Y = (rectBound.Height >> 1) - segmentInterval;
            pathPointCollection[5].X = rectBound.Width - segmentWidth;
            pathPointCollection[5].Y = (rectBound.Height >> 1) - segmentWidth * 0.5f - segmentInterval;
            m_CachedPaths[1].AddPolygon(pathPointCollection);
            m_CachedPaths[1].CloseFigure();
            if (UseItalicStyle) m_CachedPaths[1].Transform(mx);

            // bottom right '|'
            pathPointCollection[0].X = rectBound.Width - segmentWidth;
            pathPointCollection[0].Y = (rectBound.Height >> 1) + segmentInterval + segmentWidth * 0.5f;
            pathPointCollection[1].X = rectBound.Width - segmentWidth * 0.5f;
            pathPointCollection[1].Y = (rectBound.Height >> 1) + segmentInterval;
            pathPointCollection[2].X = rectBound.Width + 1;
            pathPointCollection[2].Y = (rectBound.Height >> 1) + segmentInterval + segmentWidth * 0.5f + 1;
            pathPointCollection[3].X = rectBound.Width + 1;
            pathPointCollection[3].Y = rectBound.Height - segmentInterval - segmentWidth * bevelRate * 2 - 1;
            pathPointCollection[4].X = rectBound.Width - segmentWidth * bevelRate;
            pathPointCollection[4].Y = rectBound.Height - segmentWidth * bevelRate - segmentInterval;
            pathPointCollection[5].X = rectBound.Width - segmentWidth;
            pathPointCollection[5].Y = rectBound.Height - segmentWidth - segmentInterval;
            m_CachedPaths[2].AddPolygon(pathPointCollection);
            m_CachedPaths[2].CloseFigure();
            if (UseItalicStyle) m_CachedPaths[2].Transform(mx);

            // bottom '-'
            pathPointCollection[0].X = segmentWidth * bevelRate + segmentInterval;
            pathPointCollection[0].Y = rectBound.Height - segmentWidth * bevelRate;
            pathPointCollection[1].X = segmentWidth + segmentInterval;
            pathPointCollection[1].Y = rectBound.Height - segmentWidth;
            pathPointCollection[2].X = rectBound.Width - segmentInterval - segmentWidth;
            pathPointCollection[2].Y = rectBound.Height - segmentWidth;
            pathPointCollection[3].X = rectBound.Width - segmentInterval - segmentWidth * bevelRate;
            pathPointCollection[3].Y = rectBound.Height - segmentWidth * bevelRate;
            pathPointCollection[4].X = rectBound.Width - segmentInterval - segmentWidth * bevelRate * 2;
            pathPointCollection[4].Y = rectBound.Height;
            pathPointCollection[5].X = segmentWidth * bevelRate * 2 + segmentInterval;
            pathPointCollection[5].Y = rectBound.Height;
            m_CachedPaths[3].AddPolygon(pathPointCollection);
            m_CachedPaths[3].CloseFigure();
            if (UseItalicStyle) m_CachedPaths[3].Transform(mx);

            // bottom left '|'
            pathPointCollection[0].X = 0f;
            pathPointCollection[0].Y = (rectBound.Height >> 1) + segmentInterval + segmentWidth * 0.5f;
            pathPointCollection[1].X = segmentWidth * 0.5f;
            pathPointCollection[1].Y = (rectBound.Height >> 1) + segmentInterval;
            pathPointCollection[2].X = segmentWidth;
            pathPointCollection[2].Y = (rectBound.Height >> 1) + segmentInterval + segmentWidth * 0.5f;
            pathPointCollection[3].X = segmentWidth;
            pathPointCollection[3].Y = rectBound.Height - segmentWidth - segmentInterval;
            pathPointCollection[4].X = segmentWidth * bevelRate;
            pathPointCollection[4].Y = rectBound.Height - segmentWidth * bevelRate - segmentInterval;
            pathPointCollection[5].X = 0f;
            pathPointCollection[5].Y = rectBound.Height - segmentInterval - segmentWidth * bevelRate * 2;
            m_CachedPaths[4].AddPolygon(pathPointCollection);
            m_CachedPaths[4].CloseFigure();
            if (UseItalicStyle) m_CachedPaths[4].Transform(mx);

            // upper left '|'
            pathPointCollection[0].X = 0f;
            pathPointCollection[0].Y = segmentWidth * bevelRate * 2 + segmentInterval;
            pathPointCollection[1].X = segmentWidth * bevelRate;
            pathPointCollection[1].Y = segmentWidth * bevelRate + segmentInterval;
            pathPointCollection[2].X = segmentWidth;
            pathPointCollection[2].Y = segmentWidth + segmentInterval;
            pathPointCollection[3].X = segmentWidth;
            pathPointCollection[3].Y = (rectBound.Height >> 1) - segmentWidth * 0.5f - segmentInterval;
            pathPointCollection[4].X = segmentWidth * 0.5f;
            pathPointCollection[4].Y = (rectBound.Height >> 1) - segmentInterval;
            pathPointCollection[5].X = 0f;
            pathPointCollection[5].Y = (rectBound.Height >> 1) - segmentWidth * 0.5f - segmentInterval;
            m_CachedPaths[5].AddPolygon(pathPointCollection);
            m_CachedPaths[5].CloseFigure();
            if (UseItalicStyle) m_CachedPaths[5].Transform(mx);

            // draw med '-'
            pathPointCollection[0].X = (segmentWidth * 0.5f) + segmentInterval;
            pathPointCollection[0].Y = (rectBound.Height >> 1);
            pathPointCollection[1].X = segmentWidth + segmentInterval;
            pathPointCollection[1].Y = (rectBound.Height >> 1) - segmentWidth * 0.5f;
            pathPointCollection[2].X = rectBound.Width - segmentInterval - segmentWidth;
            pathPointCollection[2].Y = (rectBound.Height >> 1) - segmentWidth * 0.5f;
            pathPointCollection[3].X = rectBound.Width - segmentInterval - segmentWidth * 0.5f;
            pathPointCollection[3].Y = rectBound.Height >> 1;
            pathPointCollection[4].X = rectBound.Width - segmentInterval - segmentWidth;
            pathPointCollection[4].Y = (rectBound.Height >> 1) + segmentWidth * 0.5f;
            pathPointCollection[5].X = segmentWidth + segmentInterval;
            pathPointCollection[5].Y = (rectBound.Height >> 1) + segmentWidth * 0.5f;
            m_CachedPaths[6].AddPolygon(pathPointCollection);
            m_CachedPaths[6].CloseFigure();
            if (UseItalicStyle) m_CachedPaths[6].Transform(mx);

            // draw dot
            pathDotCollection[0].X = 0f;
            pathDotCollection[0].Y = rectBound.Height;
            pathDotCollection[1].X = segmentWidth;
            pathDotCollection[1].Y = rectBound.Height;
            pathDotCollection[2].X = segmentWidth;
            pathDotCollection[2].Y = rectBound.Height - segmentWidth;
            pathDotCollection[3].X = 0;
            pathDotCollection[3].Y = rectBound.Height - segmentWidth;
            m_CachedPaths[7].AddPolygon(pathDotCollection);
            m_CachedPaths[7].CloseFigure();
            if (UseItalicStyle) m_CachedPaths[7].Transform(mx);
            // ok change state
            m_bIsCacheBuild = true;
        }
Example #31
0
        /// <summary>
        /// 扭曲图片校正
        /// </summary>
        public Bitmap ReSetBitMap()
        {
            Graphics g = Graphics.FromImage(bmpobj);
            Matrix X = new Matrix();
            //  X.Rotate(30);
            X.Shear((float)0.16666666667, 0);   //  2/12
            g.Transform = X;
            // Draw image
            //Rectangle cloneRect = GetPicValidByValue(128);  //Get Valid Pic Rectangle
            Rectangle cloneRect = new Rectangle(0, 0, bmpobj.Width, bmpobj.Height);
            Bitmap tmpBmp = bmpobj.Clone(cloneRect, bmpobj.PixelFormat);
            g.DrawImage(tmpBmp,
                new Rectangle(0, 0, bmpobj.Width, bmpobj.Height),
                 0, 0, tmpBmp.Width,
                 tmpBmp.Height,
                 GraphicsUnit.Pixel);

            return tmpBmp;
        }
Example #32
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));
        }
        //
        // GET: /Admin/DataCaptcha/
        public ActionResult Show()
        {
            var randomText = GenerateRandomText(6);
            var hash = ComputeMd5Hash(randomText + GetSalt());
            Session["CaptchaHash"] = hash;

            var rnd = new Random();
            var fonts = new[] { "Narkisim,Arial" };
            float orientationAngle = rnd.Next(0, 359);
            float y = 0;
            Brush brush = new SolidBrush(Color.FromArgb(255, 56, 62, 167));
            Brush brush1 = new SolidBrush(Color.White);
            Font font;
            font = new Font("Terminal", 16);
            const int height = 40;
            const int width = 100;
            var index0 = rnd.Next(0, fonts.Length);
            var familyName = fonts[index0];

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

               /* if (set == 1)
                {
                    var gradientBrush = new LinearGradientBrush(new Rectangle(0, 0, width, height),

                         Color.FromArgb(238, 240, 241, 240), Color.FromArgb(238, 240, 241, 240)

                    , orientationAngle);

                    g.FillRectangle(gradientBrush, 0, 0, width, height);
                }
               */

                    var gradientBrush = new LinearGradientBrush(new Rectangle(0, 0, width, height),

                            Color.White, Color.White

                       , orientationAngle);

                    g.FillRectangle(gradientBrush, 0, 0, width, height);

                //DrawRandomLines(ref g, width, height);
                float x = 0;
                //g.SmoothingMode = SmoothingMode.AntiAlias;
                //  g.TextRenderingHint = TextRenderingHint.AntiAlias;
                font = new Font("Constantia,Tahoma", 30, FontStyle.Italic | FontStyle.Bold, GraphicsUnit.World);
                //g.DrawString(randomText, font, brush, x,-10);

                var rec = new Rectangle(-30, 4, width, height);
                var path = new GraphicsPath();
                path.AddString(randomText, font.FontFamily, (int)FontStyle.Italic | (int)FontStyle.Bold, 30, new Point                 (-5, 10), StringFormat.GenericTypographic);

                // Determine physical size of the character when rendered
                var area = Rectangle.Round(path.GetBounds());

                // Slide it to be centered in the specified bounds
                var offset = new Point(rec.Left + (rec.Width / 2 - area.Width / 2) - area.Left, rec.Top + (rec.Height /                2 - area.Height / 2) - area.Top);
                var translate = new Matrix();
                translate.Translate(offset.X, offset.Y);
                translate.Rotate(-10, MatrixOrder.Append);
                translate.Shear(1, 0, MatrixOrder.Append);

                path.Transform(translate);

                // Now render it however desired
                g.SmoothingMode = SmoothingMode.AntiAlias;
                g.TextRenderingHint = TextRenderingHint.AntiAlias;
                g.FillPath(SystemBrushes.ControlText, path);

                for (var i = 0; i < width; i += 2)
                {
                    for (var j = 0; j < height; j += 2)
                    {
                        var offset1 = Math.Abs(height / 2 - j);
                        if (i + offset1 < width)
                        {
                            var pixel = bmpOut.GetPixel(i + offset1, j);
                            bmpOut.SetPixel(i, j, pixel);
                        }
                    }
                }

                var ms = new MemoryStream();
                bmpOut.Save(ms, ImageFormat.Png);
                var bmpBytes = ms.GetBuffer();
                bmpOut.Dispose();
                ms.Close();

                return new FileContentResult(bmpBytes, "image/png");
            }
        }