Scale() public method

public Scale ( float scaleX, float scaleY ) : void
scaleX float
scaleY float
return void
Example #1
0
		private void InitializeBitmap()
		{
			m_Bitmap = new Bitmap(m_PictureBox.Width, m_PictureBox.Height);
			m_Graphics = Graphics.FromImage(m_Bitmap);

			Matrix matrix = new Matrix();
			matrix.Scale(1.0f, -1.0f);
			matrix.Translate(m_OriginX, m_OriginY);
			matrix.Translate(m_TranslationX, m_TranslationY);
			matrix.Scale(m_ZoomFactor, m_ZoomFactor);

			m_Graphics.Transform = matrix;
		}
 public virtual void Scale(float X, float Y)
 {
     Matrix tempMatrix = new Matrix();
     tempMatrix.Scale(X,Y);
     tempMatrix.Multiply(TransformationMatrix);
     TransformationMatrix = tempMatrix;
 }
Example #3
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 #4
0
        //----------------------------------------------------------
        //--------------------- METHODES --------------------------
        //----------------------------------------------------------
        public override void Dessine(Graphics g, Point offsetPoint, float XScale, float YScale)
        {
            Matrix m = new Matrix();
            m.Scale(XScale, YScale);
            g.Transform = m;

            if (this.GradientForTup.isEnabled== true)
            {

                LinearGradientBrush br = null;

                Rectangle rectDest = new Rectangle(new Point(this.Location.X + offsetPoint.X, this.Location.Y + offsetPoint.Y), this.Size);
                br = this.GradientForTup.getBrushForDrawing(rectDest,255);
                g.FillRectangle(br, rectDest);

            }
            else
            {
            }

            SolidBrush brBottom = new SolidBrush(Color.FromArgb(this.BottomFillAlpha, this.BottomFillColor));
            g.FillRectangle(brBottom, new Rectangle(new Point(this.Location.X + offsetPoint.X, this.Location.Y + this.Size.Height / 2 + offsetPoint.Y), new Size(this.Size.Width, this.Size.Height / 2)));

               /* if (this.backgroundImage != null)
            {
                g.DrawImage(this.backgroundImage, new Rectangle(new Point(this.location.X+offsetPoint.X,this.location.Y+offsetPoint.Y), this.size));
            }
            else
            {

            }*/
        }
        /// <summary>
        /// Returned points 1-4 are the left track, points 5-8 are the right track, 9-16 are the turret
        /// They should be drawn individually
        /// </summary>
        public static PointF[] TankPolygonPoints(int offsetX, int offsetY, float rotDegrees, float size)
        {
            var points = new PointF[16] {
                // Left track
                new PointF(-1, -1),
                new PointF(-1, 1),
                new PointF(-0.5f, 1),
                new PointF(-0.5f, -1),

                // Right track
                new PointF(0.5f, -1),
                new PointF(1, -1),
                new PointF(1, 1),
                new PointF(0.5f, 1),

                // Turret
                new PointF(-0.5f, -0.5f),
                new PointF(0.5f, -0.5f),
                new PointF(-0.5f, 0.5f),
                new PointF(-0.25f, 0.5f),
                new PointF(-0.25f, 1.75f),
                new PointF(0.25f, 1.75f),
                new PointF(0.25f, 0.5f),
                new PointF(0.5f, 0.5f)
            };

            var matrix = new Matrix();
            matrix.Rotate(rotDegrees, MatrixOrder.Append);
            matrix.Translate(offsetX, offsetY, MatrixOrder.Append);
            matrix.Scale(size, size);
            matrix.TransformPoints(points);
            return points;
        }
Example #6
0
        internal void Draw(Graphics g)
        {
            GraphicsPath p = DrawDynamic();

            if (p == null)
            {
                DrawStatic(g);
                return;
            }

            System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix();
            m.Scale(OwningScene.DrawingScale, OwningScene.DrawingScale);
            m.Rotate(Body.Rotation);
            m.Translate(Body.Position.X, Body.Position.Y);
            p.Transform(m);

            if (Mode == DrawMode.Draw)
            {
                g.DrawPath(new Pen(DrawColor), p);
            }
            else
            {
                g.FillPath(new SolidBrush(DrawColor), p);
            }
        }
Example #7
0
        /// <summary>
        /// Get the desired Rounded Rectangle path.
        /// </summary>
        private GraphicsPath GetLine(RectangleF baseRect)
        {
            float x1 = (float)X1;
            float y1 = (float)Y1;
            float x2 = (float)X2;
            float y2 = (float)Y2;

            float w = (float)Math.Sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));

            float ang = (y2 - y1) / (x2 - x1);

            ang  = (float)Math.Atan(ang);
            ang *= (float)(180.0f / Math.PI);
            GraphicsPath mPath = new GraphicsPath();

            System.Drawing.Rectangle r = new System.Drawing.Rectangle((int)x1, (int)y1, (int)w, (int)StrokeThickness);
            mPath.AddRectangle(r);
            mPath.CloseFigure();

            using (Matrix matrix = new Matrix())
            {
                matrix.RotateAt(ang, new PointF(x1, y1), MatrixOrder.Append);
                matrix.Translate(baseRect.X, baseRect.Y, MatrixOrder.Append);
                RectangleF bounds = mPath.GetBounds(matrix);
                matrix.Scale(baseRect.Width / bounds.Width, baseRect.Height / bounds.Height);
                mPath.Transform(matrix);
            }
            mPath.Flatten();

            return(mPath);
        }
Example #8
0
        public int GetSelectedPhrase(Point location, float scale, Point Translate)
        {
            System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix();
            //m.Translate(Translate.X, Translate.Y, MatrixOrder.Append);
            m.Scale(scale, scale, System.Drawing.Drawing2D.MatrixOrder.Append);

            System.Drawing.Drawing2D.Matrix mt = new System.Drawing.Drawing2D.Matrix();
            mt.Translate(Translate.X, Translate.Y, MatrixOrder.Append);
            mt.Scale(scale, scale, System.Drawing.Drawing2D.MatrixOrder.Append);

            //e.IGraphics.Transform = m;
            Point[] scaledps = new Point[] { new Point(28, 28) };
            for (int i = phrases.Count - 1; i >= 0; i--)
            {
                Point[] scaledp = new Point[] { new Point(phrases[i].position.X - 4, phrases[i].position.Y - 4) };

                //scaledp
                mt.TransformPoints(scaledp);
                m.TransformPoints(scaledps);
                if (Program.HitTest(location.X, location.Y,
                                    scaledp[0].X, scaledp[0].Y, scaledps[0].X, scaledps[0].Y))
                {
                    return(i);
                }
            }
            return(-1);
        }
Example #9
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 #10
0
    /// <summary>
    /// Demonstrates the use of XGraphics.Transform.
    /// </summary>
    public override void RenderPage(XGraphics gfx)
    {
      //gfx.Clear(this.properties.General.BackColor.Color);
      base.RenderPage(gfx);

      gfx.DrawLine(XPens.MediumSlateBlue, 0, 0, 150, 200);
      gfx.DrawPolygon(properties.Pen1.Pen, GetPentagram(75, new PointF(150, 200)));

      Matrix matrix = new Matrix();
      //matrix.Scale(2f, 1.5f);
      //matrix.Translate(-200, -400);
      //matrix.Rotate(45);
      //matrix.Translate(200, 400);
      //gfx.Transform = matrix;
      //gfx.TranslateTransform(50, 30);

#if true
      gfx.TranslateTransform(30, 40, XMatrixOrder.Prepend);
      gfx.ScaleTransform(2.0f, 2.0f, XMatrixOrder.Prepend);
      gfx.RotateTransform(15, XMatrixOrder.Prepend);
#else
      gfx.TranslateTransform(30, 40, XMatrixOrder.Append);
      gfx.ScaleTransform(2.0f, 2.0f, XMatrixOrder.Append);
      gfx.RotateTransform(15, XMatrixOrder.Append);
#endif
      bool id = matrix.IsIdentity;
      matrix.Scale(2.0f, 2.0f, MatrixOrder.Prepend);
      //matrix.Translate(30, -50);
      matrix.Rotate(15, MatrixOrder.Prepend);
      //Matrix mtx = gfx.Transform.ToGdiMatrix();
      //gfx.Transform = matrix;

      gfx.DrawLine(XPens.MediumSlateBlue, 0, 0, 150, 200);
      gfx.DrawPolygon(properties.Pen2.Pen, GetPentagram(75, new PointF(150, 200)));
    }
 public override void OnPaint(PaintEventArgs e, ViewPortData viewPortData)
 {
     Graphics graphics = e.Graphics;
     Bitmap memoryBitmap = viewPortData.MemoryBitmap;
     Rectangle rect = new Rectangle(Point.Empty, memoryBitmap.Size);
     graphics.FillRectangle(AmbientTheme.WorkspaceBackgroundBrush, rect);
     if (((base.parentView.RootDesigner != null) && (base.parentView.RootDesigner.Bounds.Width >= 0)) && (base.parentView.RootDesigner.Bounds.Height >= 0))
     {
         GraphicsContainer container = graphics.BeginContainer();
         Matrix matrix = new Matrix();
         matrix.Scale(viewPortData.Scaling.Width, viewPortData.Scaling.Height, MatrixOrder.Prepend);
         Point[] pts = new Point[] { viewPortData.LogicalViewPort.Location };
         matrix.TransformPoints(pts);
         matrix.Translate((float) (-pts[0].X + viewPortData.ShadowDepth.Width), (float) (-pts[0].Y + viewPortData.ShadowDepth.Height), MatrixOrder.Append);
         graphics.Transform = matrix;
         using (Region region = new Region(ActivityDesignerPaint.GetDesignerPath(base.parentView.RootDesigner, false)))
         {
             Region clip = graphics.Clip;
             graphics.Clip = region;
             AmbientTheme ambientTheme = WorkflowTheme.CurrentTheme.AmbientTheme;
             graphics.FillRectangle(Brushes.White, base.parentView.RootDesigner.Bounds);
             if (ambientTheme.WorkflowWatermarkImage != null)
             {
                 ActivityDesignerPaint.DrawImage(graphics, ambientTheme.WorkflowWatermarkImage, base.parentView.RootDesigner.Bounds, new Rectangle(Point.Empty, ambientTheme.WorkflowWatermarkImage.Size), ambientTheme.WatermarkAlignment, 0.25f, false);
             }
             graphics.Clip = clip;
         }
         graphics.EndContainer(container);
     }
 }
        /// <summary>
        /// Creates an RTF string for an image that shows the effector graph.
        /// </summary>
        /// <param name="controlPoints">The control points for the effector.</param>
        /// <returns></returns>
        public string createEffectorImage(PointF[] controlPoints)
        {
            string imageString = null;
            string rtfString   = null;
            // !!!! Replace with getEffectorImage !!!
            int margin = 10;
            int w = 256, h = 256;

            using (Bitmap bm = new Bitmap(w, h)) {
                using (Graphics g = Graphics.FromImage(bm)) {
                    g.Clear(Color.Red);
                    g.Clear(Color.FromArgb(255, 191, 191, 191));
                    GraphicsPath gp = new GraphicsPath();
                    gp.AddLine(0, 0, 1, 0);
                    gp.AddLine(0, 1, 1, 1);
                    gp.AddLine(1, 1, 0, 1);
                    gp.AddLine(0, 0, 0, 0);
                    // Scale it
                    Matrix m = new System.Drawing.Drawing2D.Matrix();
                    m.Scale(w - 2 * margin, h - 2 * margin);
                    m.Translate(margin, margin);
                    gp.Transform(m);
                    // Draw it
                    using (Pen pen = new Pen(Color.Black)) {
                        g.DrawPath(pen, gp);
                    }
                }
                // Convert to bytes
                using (MemoryStream ms = new MemoryStream()) {
                    bm.Save(ms, ImageFormat.Png);
                    byte[] bytes      = ms.ToArray();
                    string byteString = BitConverter.ToString(bytes, 0);
                    if (!String.IsNullOrEmpty(byteString))
                    {
                        imageString = byteString.Replace("-", string.Empty);
                    }
                }
            }
#if false
            // Test
            string fileName    = @"C:\Users\evans\Pictures\Icon Images\BlueMouse.96x96.png";
            byte[] bytes1      = System.IO.File.ReadAllBytes(fileName);
            string byteString1 = BitConverter.ToString(bytes1, 0);
            if (!String.IsNullOrEmpty(byteString1))
            {
                imageString = byteString1.Replace("-", string.Empty);
            }
#endif

            // Convert to an RTF string
            if (!String.IsNullOrEmpty(imageString))
            {
                rtfString = @"{\pict\pngblip"
                            + @"\picw" + w.ToString() + @"\pich" + h.ToString()
                            + @"\picwgoal" + w.ToString() + @"\pichgoal" + h.ToString()
                            + @" " + imageString + "}";
            }
            return(rtfString);
        }
        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 #14
0
 public static Matrix ScaleBitmapMatrix(Matrix m)
 {
     System.Drawing.Drawing2D.Matrix mx =
         new System.Drawing.Drawing2D.Matrix(m.ScaleX, m.Rotate0, m.Rotate1, m.ScaleY, m.TranslateX, m.TranslateY);
     mx.Scale(1 / 20F, 1 / 20F);
     float[] els = mx.Elements;
     return new Matrix(els[0], els[1], els[2], els[3], els[4], els[5]);
 }
Example #15
0
 /// <summary>Expands the triangle by the specified length and width, keepings its center position constant.</summary>
 /// <param name="width">The number of units to add to the width.</param>
 /// <param name="height">The number of units to add to the height.</param>
 public void Scale(float width, float height)
 {
     using (System.Drawing.Drawing2D.Matrix trans = new System.Drawing.Drawing2D.Matrix())
     {
         trans.Scale(width, height);
         trans.TransformPoints(new PointF[] { this.PointA, this.PointB, this.PointC });
     }
 }
Example #16
0
 public static Matrix ScaleBitmapMatrix(Matrix m)
 {
     System.Drawing.Drawing2D.Matrix mx =
         new System.Drawing.Drawing2D.Matrix(m.ScaleX, m.Rotate0, m.Rotate1, m.ScaleY, m.TranslateX, m.TranslateY);
     mx.Scale(1 / 20F, 1 / 20F);
     float[] els = mx.Elements;
     return(new Matrix(els[0], els[1], els[2], els[3], els[4], els[5]));
 }
Example #17
0
        void generateTransformMat()
        {
            mTransformMat = new Matrix();
            mTransformMat.Translate(mTranslation.X, mTranslation.Y);
            mTransformMat.Scale(mZoomAmt.Value, mZoomAmt.Value, MatrixOrder.Append);

            mTransformMatInv = mTransformMat.Clone();
            mTransformMatInv.Invert();
        }
Example #18
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 #19
0
        private void drawGraphLine(Graphics graphics, PointF[] points, Pen pen, float yScale, float xScale)
        {
            var matrix = new Matrix();
            matrix.Scale(xScale, yScale);
            matrix.Translate(5, 5, MatrixOrder.Append);
            matrix.TransformPoints(points);

            graphics.DrawLines(pen, points);
        }
Example #20
0
 public ImageEdit()
 {
     InitializeComponent();
     SetStyle(ControlStyles.AllPaintingInWmPaint, true);
     SetStyle(ControlStyles.UserPaint, true);
     SetStyle(ControlStyles.DoubleBuffer, true);
     _transform = new Matrix();
     _transform.Scale(1, 1);
     _scale = 1;
 }
Example #21
0
 /// <summary>
 /// Will return a copy of the Transform currently used to map the world Space of the draw Set to the pixel Space of the screen
 /// </summary>
 /// <returns></returns>
 public void setInverseCameraTransform()
 {
     inverseCameraTransform = cameraTransform.Clone();
     inverseCameraTransform.Invert();
     //adjusting for any warping as a result of differently sized buffers
     if (drawBuffers != null && (drawBuffers[0].Width != base.Width || drawBuffers[0].Height != base.Height))
     {
         inverseCameraTransform.Scale(base.Width / drawBuffers[0].Width, base.Height / drawBuffers[0].Height, MatrixOrder.Append);
     }
 }
 private void CalcTransform()
 {
     Matrix m = new Matrix();
     m.Translate(Width / 2, Height / 2);
     m.Scale((float)zoom, (float)zoom);
     m.Translate(offset.X, offset.Y);
     transform = m;
     itransform = m.Clone();
     itransform.Invert();
 }
Example #23
0
        public QuotePartButton(float scaleX, float scaleY, BrushesStorage brushes, PenStorage pens, bool isLeft = true)
        {
            brushesStor = brushes;
            pensStor = pens;
            colorScheme.Add(ButtonFigureColorScheme.Normal, Color.FromArgb(255, 180, 247, 180));
            colorScheme.Add(ButtonFigureColorScheme.Pressed, Color.FromArgb(255, 200, 247, 210));
            colorScheme.Add(ButtonFigureColorScheme.Light, Color.FromArgb(255, 160, 195, 180));

            currentBrush = brushesStor.GetBrush(colorScheme[ButtonFigureColorScheme.Normal]) as SolidBrush;

            ScaleX = scaleX;
            ScaleY = scaleY;
            this.isLeft = isLeft;
            translateMatrix = new Matrix();

            string buySellIndicatorHaderText;
            if (isLeft)
            {
                translateMatrix.Translate(paddingLeftRightProportion / 2, PaddingTopProportion);
                buySellIndicatorHaderText = "Bid";
            }
            else
            {
                translateMatrix.Translate(QuotePartButtonFigure.OriginalWidth * 2 + paddingLeftRightProportion / 2, PaddingTopProportion);
                translateMatrix.Scale(-1, 1);
                buySellIndicatorHaderText = "Ask";
            }

            buySellIndicator = new BuySellIndicator
                                   {
                                       ScaleX = scaleX,
                                       ScaleY = scaleY,
                                       OriginalLocation = isLeft
                                            ?
                                            new Point(
                                                Convert.ToInt32(paddingLeftRightProportion),
                                                Convert.ToInt32(PaddingTopProportion + PaddingTopBuySellIndicator))
                                            :
                                            new Point(
                                                Convert.ToInt32(QuotePartButtonFigure.OriginalWidth + paddingLeftRightProportion),
                                                Convert.ToInt32(PaddingTopProportion + PaddingTopBuySellIndicator)),
                                       HaderText = buySellIndicatorHaderText,
                                       Volume = null
                                   };

            arrowTrend = new ArrowTrend
                             {
                                 Sx = ScaleX,
                                 Sy = ScaleY,
                                 Brushes = brushes,
                                 Pens = pens,
                                 OriginalLocation = isLeft ? new PointF(QuotePartButtonFigure.OriginalWidth - paddingLeftRightProportion - 2, PaddingTopArrow) :
                                                             new PointF(QuotePartButtonFigure.OriginalWidth * 2 - paddingLeftRightProportion - 2, PaddingTopArrow)
                             };
        }
Example #24
0
        public static void DrawLinesGdi32(this Graphics g, Pen pen, List<PointF> points)
        {
            float scaleX, scaleY;

            if (g.PageUnit == GraphicsUnit.Millimeter)
            {
                scaleX = g.DpiX / 25.4f;
                scaleY = g.DpiY / 25.4f;
            }
            else
            {
                scaleX = 1.0f;
                scaleY = 1.0f;
            }

            Matrix transform = g.Transform;
            Matrix scale = new Matrix();
            scale.Scale(scaleX, scaleY);

            transform.Multiply(scale, MatrixOrder.Append);

            IntPtr hDC = g.GetHdc();
            IntPtr hPen = Gdi32.CreatePen(0, (int)pen.Width, pen.Color.ToGdi32RGB());
            Gdi32.SelectObject(hDC, hPen);

            //var pointsArray = points.ToArray();
            //transform.TransformPoints(pointsArray); // <-- extremely slow, faster is to manually transform each point

            float[] m = transform.Elements;
            PointF pt;
            int x, y;

            // | m[0] m[1] m[4] |
            // | m[2] m[3] m[5] |

            // x' = x * m[0] + y * m[1] + m[4]
            // y' = x * m[2] + y * m[3] + m[5]

            pt = points[0];
            x = (int)(pt.X * m[0] + pt.Y * m[1] + m[4] + 0.5f);
            y = (int)(pt.X * m[2] + pt.Y * m[3] + m[5] + 0.5f);
            Gdi32.MoveToEx(hDC, x, y, ref _nullPoint);

            for (int i = 1; i < points.Count; i++)
            {
                pt = points[i];
                x = (int)(pt.X * m[0] + pt.Y * m[1] + m[4] + 0.5f);
                y = (int)(pt.X * m[2] + pt.Y * m[3] + m[5] + 0.5f);
                Gdi32.LineTo(hDC, x, y);
            }

            Gdi32.DeleteObject(hPen);
            g.ReleaseHdc(hDC);
        }
Example #25
0
    /// <summary>
    /// Demonstrates the use of XGraphics.Transform.
    /// </summary>
    public override void RenderPage(XGraphics gfx)
    {
      base.RenderPage(gfx);

      //XGraphicsState state = gfx.Save();

      gfx.Save();
      gfx.IntersectClip(new XRect(20, 20, 300, 500));
      gfx.DrawRectangle(XBrushes.Yellow, 0, 0, gfx.PageSize.Width, gfx.PageSize.Height);
      gfx.Restore();

      gfx.Save();
      gfx.IntersectClip(new XRect(100, 200, 300, 500));
      gfx.DrawRectangle(XBrushes.LightBlue, 0, 0, gfx.PageSize.Width, gfx.PageSize.Height);

      gfx.DrawLine(XPens.MediumSlateBlue, 0, 0, 150, 200);
      gfx.DrawPolygon(properties.Pen1.Pen, GetPentagram(75, new PointF(150, 200)));


      Matrix matrix = new Matrix();
      //matrix.Scale(2f, 1.5f);
      //matrix.Translate(-200, -400);
      //matrix.Rotate(45);
      //matrix.Translate(200, 400);
      //gfx.Transform = matrix;
      //gfx.TranslateTransform(50, 30);

#if true
      gfx.TranslateTransform(30, 40, XMatrixOrder.Prepend);
      gfx.ScaleTransform(2.0f, 2.0f, XMatrixOrder.Prepend);
      gfx.RotateTransform(15, XMatrixOrder.Prepend);
#else
      gfx.TranslateTransform(30, 40, XMatrixOrder.Append);
      gfx.ScaleTransform(2.0f, 2.0f, XMatrixOrder.Append);
      gfx.RotateTransform(15, XMatrixOrder.Append);
#endif
      bool id = matrix.IsIdentity;
      matrix.Scale(2.0f, 2.0f, MatrixOrder.Prepend);
      //matrix.Translate(30, -50);
      matrix.Rotate(15, MatrixOrder.Prepend);
      //Matrix mtx = gfx.Transform.ToGdiMatrix();
      //gfx.Transform = matrix;

      gfx.DrawLine(XPens.MediumSlateBlue, 0, 0, 150, 200);
      gfx.DrawPolygon(properties.Pen2.Pen, GetPentagram(75, new PointF(150, 200)));

      gfx.Restore();

      gfx.DrawLine(XPens.Red, 0, 0, 1000, 1000);

      gfx.DrawPolygon(XPens.SandyBrown, GetPentagram(75, new PointF(150, 200)));

    }
Example #26
0
 /// <summary>
 /// фун для матричного преобразования в даном случае увеличения
 /// </summary>
 /// <param name="temp"></param>
 public void myMatrixTransformScale(ref LittleShape2 temp)
 {
     System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix();
     System.Drawing.Drawing2D.Matrix test   = new System.Drawing.Drawing2D.Matrix(1, 0, 0, 1, 0, 0);
     // трансформация  из double[,] в pointF[]
     PointF[] arr = temp.getPointF(rank);
     // увеличение
     matrix.Scale(50, 50);
     // применение увеличения
     matrix.TransformPoints(arr);
     // уже увеличеная фигура (точки)
     temp.setPointF(arr);
 }
        // ---------------------------------------------------------------------------
        /**
         * Creates a PDF document.
         */
        public byte[] CreatePdf()
        {
            // step 1
              Rectangle rect = new Rectangle(-595, -842, 595, 842);
              using (MemoryStream ms = new MemoryStream()) {
            using (Document document = new Document(rect)) {
              // step 2
              PdfWriter writer = PdfWriter.GetInstance(document, ms);
              // step 3
              document.Open();
              // step 4
              PdfContentByte canvas = writer.DirectContent;
              // draw coordinate system
              canvas.MoveTo(-595, 0);
              canvas.LineTo(595, 0);
              canvas.MoveTo(0, -842);
              canvas.LineTo(0, 842);
              canvas.Stroke();
              // read the PDF with the logo
              PdfReader reader = new PdfReader(RESOURCE);
              PdfTemplate template = writer.GetImportedPage(reader, 1);
              // add it
              canvas.SaveState();
              canvas.AddTemplate(template, 0, 0);
              Matrix matrix = null;
              using ( matrix = new Matrix() ) {
            matrix.Translate(-595, 0);
            matrix.Scale(0.5f, 0.5f);
            canvas.Transform(matrix);
            canvas.AddTemplate(template, 0, 0);
            matrix = new Matrix(1f, 0f, 0f, 1f, 595f, 595f);
            canvas.AddTemplate(template, matrix);
            canvas.RestoreState();

            canvas.SaveState();
            matrix = new Matrix(1f, 0f, 0.4f, 1f, -750f, -650f);
            canvas.AddTemplate(template, matrix);
            canvas.RestoreState();

            canvas.SaveState();
            matrix = new Matrix(0, -1, -1, 0, 650, 0);
            canvas.AddTemplate(template, matrix);
            matrix = new Matrix(0, -0.2f, -0.5f, 0, 350, 0);
            canvas.AddTemplate(template, matrix);
            canvas.RestoreState();
              }
            }
            return ms.ToArray();
              }
        }
        private static void DrawPointMass(IPointMass pointMass, Pen pen, Brush brush, Graphics g)
        {
            var triangle = new[] { new PointF(1, 0), new PointF(-0.7f, 0.7f), new PointF(-0.7f, -0.7f) };

            using (var m = new Matrix())
            {
                m.Translate(pointMass.Position.X, pointMass.Position.Y);
                m.Rotate((float)(Math.Atan2(pointMass.Velocity.Y, pointMass.Velocity.X) * 180 / Math.PI));
                m.Scale(pointMass.Radius*0.9f, pointMass.Radius*0.9f);
                m.TransformPoints(triangle);
            }

            g.FillPolygon(brush, triangle);
            g.DrawCircle(pen, pointMass.Position, pointMass.Radius);
        }
Example #29
0
        private AdvancedPath GetClippingPath(float dpi = 72)
        {
            var path = GetPath();

            if (!Utils.EqualsOfFloatNumbers(dpi, 72))
            {
                using (var matrix = new Matrix())
                {
                    matrix.Scale(dpi / 72, dpi / 72, MatrixOrder.Append);
                    path.ApplyTransform(matrix);
                }
            }

            return(path);
        }
        public static Point[] MinePolygonPoints(int offsetX, int offsetY, float size)
        {
            var points = new Point[4] {
                new Point(-1, -1),
                new Point(-1, 1),
                new Point(1, 1),
                new Point(1, -1)
            };

            var matrix = new Matrix();
            matrix.Translate(offsetX, offsetY);
            matrix.Scale(size, size);
            matrix.TransformPoints(points);
            return points;
        }
        public static Icon TankIcon()
        {
            var bitmap = new Bitmap(32, 32);
            using (var g = Graphics.FromImage(bitmap))
            {
                var points = TankPolygonPoints(16, 16, 180, 5);
                var matrix = new Matrix();
                matrix.Scale(1.5f, 1.5f);
                matrix.Translate(-5, -5);
                matrix.TransformPoints(points);

                var pen = new Pen(Color.Black);
                g.DrawPolygon(pen, points);
                g.FillPolygon(pen.Brush, points);
                pen.Dispose();
            }
            return Icon.FromHandle(bitmap.GetHicon());
        }
    /// <summary>
    /// Modifies clipping path explicitly using memory-friendly Pipeline API
    /// </summary>
    private static void ModifyClippingPathExplicitlyMemoryFriendly()
    {
        int width  = 1000;
        int height = 1000;

        using (var reader = new JpegReader("../../../../_Input/Apple.jpg"))
            using (var generator = new ImageGenerator(width, height, reader.PixelFormat, RgbColor.White))
                using (var combiner = new Combiner(CombineMode.Copy))
                    using (var writer = new JpegWriter("../../../../_Output/ModifyClippingPathExplicitlyMemoryFriendly.jpg"))
                    {
                        combiner.TopImage = reader;
                        combiner.X        = (width - reader.Width) / 2;
                        combiner.Y        = (height - reader.Height) / 2;

                        // The clipping path has relatives coordinates (0.0f ... 1.f0). So we need to transform it.
                        var transform = new System.Drawing.Drawing2D.Matrix();
                        transform.Scale((float)reader.Width / (float)width, (float)reader.Height / (float)height);
                        transform.Translate((float)combiner.X / (float)reader.Width, (float)combiner.Y / (float)reader.Height);

                        var adobeResources = reader.AdobeResources;

                        // Remove clipping paths
                        foreach (long key in adobeResources.Keys)
                        {
                            if (key >= FirstPathId && key <= LastPathId)
                            {
                                adobeResources.Remove(key);
                            }
                        }

                        // Transform and save clipping paths
                        for (var i = 0; i < reader.ClippingPaths.Count; i++)
                        {
                            var clippingPath = reader.ClippingPaths[i];
                            clippingPath.ApplyTransform(transform);

                            adobeResources.Add(FirstPathId + i, new AdobeResourceBlock(clippingPath.Name, clippingPath.Data));
                        }

                        writer.AdobeResources = adobeResources;

                        Pipeline.Run(generator + combiner + writer);
                    }
    }
Example #33
0
        Matrix2D trans_D2C;         //显示拓扑坐标系(原点在minx,miny处)->窗口客户区坐标系

        void UpdateMapping()        //更新映射关系
        {
            int offset_x = (ClientSize.Width - bmp.Width) / 2;
            int offset_y = (ClientSize.Height - bmp.Height) / 2;

            trans_D2C = new Matrix2D(1, 0, 0, -1, 0, display.maxy);                 //Y翻转
            trans_D2C.Scale(1 / zoom, 1 / zoom, MatrixOrder.Append);                //再缩放
            trans_D2C.Translate(offset_x, offset_y, MatrixOrder.Append);            //再平移
            trans_D2C.Translate(delta.X, delta.Y, MatrixOrder.Append);              //再平移(鼠标平移分量)

            //trans_C2D = new Matrix2D();
            //trans_C2D.Translate(-delta.X, -delta.Y, MatrixOrder.Append);	//先抵消鼠标平移分量
            //trans_C2D.Translate(-offset_x, -offset_y, MatrixOrder.Append);	//先平移回原点
            //trans_C2D.Scale(zoom, zoom, MatrixOrder.Append);				//反向缩放
            //trans_C2D.Multiply(new Matrix2D(1, 0, 0, -1, 0, display.maxy), MatrixOrder.Append);//颠倒Y坐标轴

            trans_C2D = trans_D2C.Clone();
            trans_C2D.Invert();
        }
        //http://www.tinaja.com/glib/bezcirc2.pdf
        private CircularBezier(PointD start, PointD center, PointD end)
        {
            double Θ = new VectorD(center, start).GetAngleWith(new VectorD(center, end));
            double φ = Θ/2;

            double x0 = Math.Cos(φ);
            double y0 = Math.Sin(φ);

            double x3 = x0;
            double y3 = -y0;

            double x1 = (4 - x0)/3;
            double y1 = ((1 - x0)*(3 - x0))/(3*y0);

            double x2 = x1;
            double y2 = -y1;

            var points = new PointF[] {new PointD(x0, y3), new PointD(x1, y2), new PointD(x2, y1), new PointD(x3, y0)};

            var matrix = new Matrix();
            matrix.Rotate(
                Convert.ToSingle(Geometrics.RadianToDegree(Math.Atan2(start.Y - center.Y, start.X - center.X) + φ)) +
                360);
            matrix.Scale(Convert.ToSingle(new LineD(start, center).Length),
                         Convert.ToSingle(new LineD(start, center).Length));
            matrix.TransformPoints(points);

            matrix = new Matrix();
            matrix.Translate(Convert.ToSingle(center.X), Convert.ToSingle(center.Y));
            matrix.TransformPoints(points);

            p0 = points[0];
            p1 = points[1];
            p2 = points[2];
            p3 = points[3];
            p0f = points[0];
            p1f = points[1];
            p2f = points[2];
            p3f = points[3];

            this.center = center;
            Length = getlength();
        }
Example #35
0
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            TimeSpan ts = DateTime.Now - last;
            last = DateTime.Now;
            string text = string.Format("FPS: {0}\nPOINTS: {1}", Math.Round(1 / ts.TotalSeconds).ToString("0"), players.Sum(x => x.pointcount));
            e.Graphics.DrawString(text, this.Font, Brushes.Black, 0, 0);

            Matrix m = new Matrix();
            m.Scale(((float)this.Height - 40f) / 600f, ((float)this.Height - 40f) / 600f);
            m.Translate(20, 20, MatrixOrder.Append);
            e.Graphics.MultiplyTransform(m);

            //player1.Draw(e.Graphics);
            players.ForEach(x => x.Draw(e.Graphics));

            e.Graphics.ResetTransform();
            e.Graphics.DrawRectangle(Pens.Blue, new Rectangle(20, 20, this.Height - 40, this.Height - 40));
        }
Example #36
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 #37
0
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            Rectangle rect = new Rectangle(30, 30, 60, 60);
            Pen penB = new Pen(Brushes.Blue,2);
            Pen penR = new Pen(Brushes.Red,2);
            // примитивы до глобального преобразования
            g.DrawRectangle(penB, rect);
            g.DrawLine(penR, 30, 200, 200, 170);
            g.FillEllipse(Brushes.Brown, new Rectangle(100, 30, 100, 100));

            Matrix X = new Matrix();
            X.Scale(1.4f, 1.4f, MatrixOrder.Append);
            X.RotateAt(-10,new PointF(0.0f,0.0f),MatrixOrder.Append);
            g.Transform = X;
            // примитивы после глобального преобразования
            g.DrawRectangle(penB, rect);
            g.DrawLine(penR, 30, 200, 200, 170);
            g.FillEllipse(Brushes.Brown, new Rectangle(100, 30, 100, 100));

        }
        /// <summary>
        /// Snap rotate to some angle. Preserve scale and translation.
        /// </summary>
        /// <param name="mat"></param>
        /// <param name="angle">__ANGLE IS IN DEGREES__</param>
        /// <returns></returns>
        public static d2d.Matrix eSnapRotate(this d2d.Matrix mat, double angle)
        {
            // Graphics tries to work opposite of OpenGL, in Drawing2D:
            // PRE - multiply for local
            // post -multiply for global
            var curmat = mat.Elements;
            // get the vector components.
            var x_axis = new ai.Vector2D(curmat[0], curmat[1]);
            var y_axis = new ai.Vector2D(curmat[2], curmat[3]);
            // Get the scale of current matrix
            double x_len  = x_axis.Length();
            double y_len  = y_axis.Length();
            var    newmat = new d2d.Matrix();

            // Preserve scale and translation
            // This means: v*M = v*(S * R * T)
            newmat.Scale((float)x_len, (float)y_len);
            newmat.Rotate((float)angle);
            newmat.Translate(curmat[4], curmat[5]);
            return(newmat.Clone());
        }
Example #39
0
        /// <summary>
        /// Paint the image
        /// </summary>
        /// <param name="pe">The paint event</param>
        protected override void OnPaint(PaintEventArgs pe)
        {
            if (IsDisposed)
            {
                return;
            }
            if (this.Image != null //image is set
                &&                 //either pan or zoom
                (_zoomScale != 1.0 ||
                 (horizontalScrollBar.Visible && horizontalScrollBar.Value != 0) ||
                 (verticalScrollBar.Visible && verticalScrollBar.Value != 0)))
            {
                if (pe.Graphics.InterpolationMode != _interpolationMode)
                {
                    pe.Graphics.InterpolationMode = _interpolationMode;
                }

                using (System.Drawing.Drawing2D.Matrix transform = pe.Graphics.Transform)
                {
                    if (_zoomScale != 1.0)
                    {
                        transform.Scale((float)_zoomScale, (float)_zoomScale, MatrixOrder.Append);
                    }

                    int horizontalTranslation = horizontalScrollBar.Visible ? -horizontalScrollBar.Value : 0;
                    int verticleTranslation   = verticalScrollBar.Visible ? -verticalScrollBar.Value : 0;
                    if (horizontalTranslation != 0 || verticleTranslation != 0)
                    {
                        transform.Translate(horizontalTranslation, verticleTranslation);
                    }

                    pe.Graphics.Transform = transform;
                    base.OnPaint(pe);
                }
            }
            else
            {
                base.OnPaint(pe);
            }
        }
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;

            Rectangle rect = new Rectangle(30, 30, 60, 60);
            Pen penBlue = new Pen(Brushes.Blue , 2);
            Pen redPen = new Pen(Brushes.Red, 2);

            g.DrawRectangle(penBlue, rect);
            g.DrawLine(redPen, 30, 200, 200, 170);
            g.DrawEllipse(new Pen(Brushes.Plum , 3) , new Rectangle(100 , 30 , 100 , 120));
            Matrix X = new Matrix();
            X.Scale(2.2f, 2.2f, MatrixOrder.Append);
            X.RotateAt(30, new PointF(0f, 0f), MatrixOrder.Append);
            g.Transform = X;

            g.DrawRectangle(penBlue, rect);
            g.DrawLine(redPen, 30, 200, 200, 170);
            g.DrawEllipse(new Pen(Brushes.Plum, 3), new Rectangle(100, 30, 100, 120));

            g.Dispose();
        }
        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.Tomato;
                pgBrush.SurroundColors = new Color[] { Color.Indigo  , Color.Khaki};
                Matrix X = new Matrix();
                X.Translate(30f, 10f, MatrixOrder.Append);
                X.Rotate(10f, MatrixOrder.Append);
                X.Scale(1.2f, 1f, MatrixOrder.Append);

                path.Transform(X);
                pgBrush.Transform = X;

                g.FillPath(pgBrush, path);
            }
        }
 public override void OnPaint(PaintEventArgs e, ViewPortData viewPortData)
 {
     base.OnPaint(e, viewPortData);
     Graphics graphics = e.Graphics;
     if (((base.parentView.RootDesigner != null) && (base.parentView.RootDesigner.Bounds.Width >= 0)) && (base.parentView.RootDesigner.Bounds.Height >= 0))
     {
         GraphicsContainer container = graphics.BeginContainer();
         Matrix matrix = new Matrix();
         matrix.Scale(viewPortData.Scaling.Width, viewPortData.Scaling.Height, MatrixOrder.Prepend);
         Point[] pts = new Point[] { viewPortData.LogicalViewPort.Location };
         matrix.TransformPoints(pts);
         matrix.Translate((float) (-pts[0].X + viewPortData.ShadowDepth.Width), (float) (-pts[0].Y + viewPortData.ShadowDepth.Height), MatrixOrder.Append);
         graphics.Transform = matrix;
         Rectangle bounds = base.parentView.RootDesigner.Bounds;
         graphics.ExcludeClip(bounds);
         bounds.Inflate(DefaultWorkflowLayout.Separator.Width / 2, DefaultWorkflowLayout.Separator.Height / 2);
         ActivityDesignerPaint.DrawDropShadow(graphics, bounds, AmbientTheme.WorkflowBorderPen.Color, 4, LightSourcePosition.Top | LightSourcePosition.Left, 0.2f, false);
         graphics.FillRectangle(WorkflowTheme.CurrentTheme.AmbientTheme.BackgroundBrush, bounds);
         graphics.DrawRectangle(AmbientTheme.WorkflowBorderPen, bounds);
         graphics.EndContainer(container);
     }
 }
Example #43
0
 private void SetupTransform()
 {
     //world points
     float x1 = 0, y1 = 0, x2 = 100, y2 = 100;
     //device points
     Rectangle crect = this.ClientRectangle;
     float x1d = (float)5 * crect.Width / 14;//up left corner
     float y1d = 0.1f * crect.Height;//up left corner
     float x2d = (float)13 * crect.Width / 14;//bottom rigth corner
     float y2d = 0.9f * crect.Height;//bottom right corner
     //calcutae the scalling
     s1 = (x1d - x2d) / (x1 - x2);
     s2 = (y1d - y2d) / (y1 - y2);
     t1 = (x1 * x2d - x2 * x1d) / (x1 - x2);
     t2 = (y1 * y2d - y2 * y1d) / (y1 - y2);
     m = new Matrix();
     m.Translate(t1, t2);//transalation
     m.Scale(s1, s2);//scaling
     //get the inverse
     m.Invert();
     minv = m.Clone();
     m.Invert();
 }
Example #44
0
		protected override void OnPaint(PaintEventArgs pea)
		{
			base.OnPaint(pea);
			if (map == null)
				return;

			ImageSegment [] segs = ExtractSegments();
			uint imageSize = ImageSize(segs);
			
			Matrix m = new Matrix();
			m.Scale(1.0F, (float)Height / (float) imageSize);
			pea.Graphics.Transform = m;

			Rectangle rc = ClientRectangle;
			ulong start = segs[0].Address.ToLinear();
			foreach (ImageSegment seg in segs)
			{
				rc.Y = (int) (seg.Address.ToLinear() - start);
				rc.Height = (int) seg.Size;

				PaintSegment(seg, pea.Graphics, rc);
			}
		}
Example #45
0
        public Main()
        {
            InitializeComponent();

            //mouse points
            prev = new Point();
            next = new Point();
            //setup coordinate transformation
            float width = this.ClientRectangle.Width;
            float height = this.ClientRectangle.Height;
            float x1d = width * 0.1f;
            float x2d = height * 0.9f;
            float x3d = width * 0.9f;
            float x4d = height * 0.1f;
            float x1 = -80, x2 = -50, x3 = 80, x4 = 50;
            s1 = (x1d - x3d) / (x1 - x3);
            float s2 = (x2d - x4d) / (x2 - x4);
            float t1 = (x1 * x3d - x1d * x3) / (x1 - x3);
            float t2 = (x2 * x4d - x2d * x4) / (x2 - x4);
            m = new Matrix();
            m.Translate(t1, t2);
            m.Scale(s1, s2);
        }
Example #46
0
        public int GetSelectedTimeLine(Point location, float scale, Point Translate)
        {
            System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix();
            m.Scale(scale, scale, System.Drawing.Drawing2D.MatrixOrder.Append);
            //e.IGraphics.Transform = m;
            System.Drawing.Drawing2D.Matrix mt = new System.Drawing.Drawing2D.Matrix();
            mt.Translate(Translate.X, Translate.Y, MatrixOrder.Append);
            mt.Scale(scale, scale, System.Drawing.Drawing2D.MatrixOrder.Append);

            for (int i = 0; i < timelines.Count; i++)
            {
                Point[] scaledp  = new Point[] { new Point(timelines[i]._dragtag.X - 4, timelines[i]._dragtag.Y - 4) };
                Point[] scaledps = new Point[] { new Point(19, 19) };
                //scaledp
                mt.TransformPoints(scaledp);
                m.TransformPoints(scaledps);
                if (Program.HitTest(location.X, location.Y,
                                    scaledp[0].X, scaledp[0].Y, scaledps[0].X, scaledps[0].Y))
                {
                    return(i);
                }
            }
            return(-1);
        }
 public void ScaleTransform(float sx, float sy)
 {
     System.Drawing.Drawing2D.Matrix M2 = new System.Drawing.Drawing2D.Matrix();
     M2.Scale(sx, sy);
     DoTransform(M2);
 }
Example #48
0
 public void ScaleTransform(float sx, float sy, MatrixOrder order)
 {
     gradientTransform.Scale(sx, sy, order);
     changed = true;
 }
Example #49
0
        private static LinearGradientBrush ExtendGradientBrush(LinearGradientBrush brush, GraphicsPath path)
        {
            // get the untransformed gradient rectangle
            RectangleF gradRect = brush.Rectangle;

            // put it into a points array starting with top right
            PointF[] gradPoints = new PointF[4]
            {
                new PointF(gradRect.Right, gradRect.Top),
                new PointF(gradRect.Right, gradRect.Bottom),
                new PointF(gradRect.Left, gradRect.Bottom),
                new PointF(gradRect.Left, gradRect.Top)
            };
            // transform the points to get the two edges of the gradient as
            // tr-br and bl-tl. The width of the gradient can be found at the bottom.
            // This makes it easier to figure out which corners need to be tested.
            brush.Transform.TransformPoints(gradPoints);

            RectangleF pathRect = path.GetBounds();

            // find the corner point to test to see if it might be past the gradient
            // first make the forward(AfBf) and back(AbBb) edge lines of the gradient
            PointF Af = gradPoints[0];
            PointF Bf = gradPoints[1];
            PointF Ab = gradPoints[2];
            PointF Bb = gradPoints[3];

            // set forward and back test corner
            PointF Cb = pathRect.Location;
            PointF Cf = pathRect.Location;

            if (Af.X >= Bf.X)
            {
                Cf.Y += pathRect.Height;
            }
            else
            {
                Cb.Y += pathRect.Height;
            }
            if (Af.Y < Bf.Y)
            {
                Cf.X += pathRect.Width;
            }
            else
            {
                Cb.X += pathRect.Width;
            }
            // gradient width is the connection lines if grad isn't skewed (same for both)
            // check if gradients can ever be skewed... if so, calc line to line dist.
            float gradW = (float)Math.Sqrt(
                (Bf.X - Ab.X) * (Bf.X - Ab.X) + (Bf.Y - Ab.Y) * (Bf.Y - Ab.Y));
            // length of gradient edge (same for both sides)
            float gradH = (float)Math.Sqrt(
                (Bf.X - Af.X) * (Bf.X - Af.X) + (Bf.Y - Af.Y) * (Bf.Y - Af.Y));

            // now check if the path data might be bigger than the gradient
            int hasFRatio = 0;
            int hasBRatio = 0;
            // in the forward direction
            float distToLineF = 0;
            float distToLineB = 0;
            float sf          = ((Af.Y - Cf.Y) * (Bf.X - Af.X) - (Af.X - Cf.X) * (Bf.Y - Af.Y)) / (gradH * gradH);

            if (sf > 0)
            {
                // graphic may be bigger than fill so
                // figure out how much bigger the fill has to be
                // (meaning how much smaller the original gradient must be)
                distToLineF = Math.Abs(sf) * gradH;
                hasFRatio   = 1;
            }
            // in the back direction
            float sb = ((Ab.Y - Cb.Y) * (Bb.X - Ab.X) - (Ab.X - Cb.X) * (Bb.Y - Ab.Y)) / (gradH * gradH);

            if (sb > 0)
            {
                distToLineB = Math.Abs(sb) * gradH;;
                hasBRatio   = 1;
            }

            // Now we have the info we need to tell if the gradient doesn't fit in the path
            if ((hasFRatio + hasBRatio) > 0)
            {
                float totalNewWidth = distToLineF + distToLineB + gradW;
                float ratioB        = distToLineB / totalNewWidth;
                float ratioF        = distToLineF / totalNewWidth;
                float compressRatio = gradW / totalNewWidth;
                float expandRatio   = totalNewWidth / gradW; // eg. 1/compressRatio

                float[]    pos     = brush.InterpolationColors.Positions;
                float[]    newPos  = new float[pos.Length + hasFRatio + hasBRatio];
                Ms.Color[] cols    = brush.InterpolationColors.Colors;
                Ms.Color[] newCols = new Ms.Color[cols.Length + hasFRatio + hasBRatio];
                if (hasBRatio == 1)
                {
                    newPos[0]  = 0;
                    newCols[0] = cols[0];
                }
                for (int i = 0; i < pos.Length; i++)
                {
                    newPos[i + hasBRatio]  = pos[i] * compressRatio + ratioB;
                    newCols[i + hasBRatio] = cols[i];
                }
                newPos[newPos.Length - 1]   = 1;
                newCols[newCols.Length - 1] = cols[cols.Length - 1];

                ColorBlend cb2 = new ColorBlend(newPos.Length);
                cb2.Positions             = newPos;
                cb2.Colors                = newCols;
                brush.InterpolationColors = cb2;

                System.Drawing.Drawing2D.Matrix m2 = brush.Transform;
                // scale it with the edge at the orgin
                m2.Translate(-Bb.X, -Bb.Y, MatrixOrder.Append);
                m2.Scale(expandRatio, expandRatio, MatrixOrder.Append);
                // now move it back to be on the back edge, whatever that is
                if (hasBRatio == 1)
                {
                    m2.Translate(Cb.X, Cb.Y, MatrixOrder.Append);
                }
                else
                {
                    m2.Translate(Bb.X, Bb.Y, MatrixOrder.Append);
                }
                brush.Transform = m2;
            }
            return(brush);
        }
Example #50
0
        private void DrawGame(Graphics graphics)
        {
            //graphics.Clear(Color.Black);

            playingArea   = new Rectangle(new Point(0, 0), form.Size);
            playingArea.X = playingArea.X + 10;
            playingArea.Y = playingArea.Y + 10;

            playingArea.Width  -= 30;
            playingArea.Height -= 50;

            graphics.DrawRectangle(new Pen(Brushes.White), playingArea.X, playingArea.Y, playingArea.Width, playingArea.Height);


            for (int i = 0; i < gameLogicToDraw.SizeY; i++)
            {
                for (int j = 0; j < gameLogicToDraw.SizeX; j++)
                {
                    float centerPointX = playingArea.X + GetCenterPoint(j, i).X;
                    float centerPointY = playingArea.Y + GetCenterPoint(j, i).Y;

                    int tileX = ConvertScreenToTileCoordsX(j);
                    int tileY = ConvertScreenToTileCoordsY(i);

                    Tile thisTile = gameLogicToDraw.Tiles[tileX, tileY];

                    for (int k = 0; k < 6; k++)
                    {
                        System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix();
                        PointF p1 = Hexagon[k];
                        PointF p2 = Hexagon[(k + 1) % 6];
                        m.Translate(centerPointX, centerPointY);
                        m.Scale(hexRadiusX, hexRadiusY);
                        p1 = m.TransformPoint(p1);
                        p2 = m.TransformPoint(p2);

                        int penWidth = 4;

                        Pen pen1;

                        Tuple <int, int> neighbouringTile = gameLogicToDraw.GetNeighbouringTile(Tuple.Create(tileX, tileY), (HexDirections)k, true);
                        Faction          thisFaction      = gameLogicToDraw.GetTile(Tuple.Create(tileX, tileY)).OccupiedByFaction;

                        if (thisFaction == Faction.Empty)
                        {
                            if (gameLogicToDraw.GetTile(gameLogicToDraw.GetNeighbouringTile(Tuple.Create(tileX, tileY), (HexDirections)k)).OccupiedByFaction == Faction.Empty)
                            {
                                pen1 = new Pen(Color.Gray, penWidth);
                                graphics.DrawLine(pen1, p1, p2);
                            }
                        }
                        else
                        {
                            if (gameLogicToDraw.IsOutOfBounds(neighbouringTile))
                            {
                                pen1 = new Pen(FactionColors[thisFaction.ID], penWidth);
                                graphics.DrawLine(pen1, p1, p2);
                            }
                            else
                            {
                                Faction neighbourFaction = gameLogicToDraw.GetTile(neighbouringTile).OccupiedByFaction;
                                if (neighbourFaction == Faction.Empty)
                                {
                                    //if (k == (int)(HexDirections.Up))

                                    pen1 = new Pen(FactionColors[thisFaction.ID], penWidth);
                                    graphics.DrawLine(pen1, p1, p2);
                                }
                                else if (neighbourFaction == thisFaction)
                                {
                                    continue;
                                }
                                else
                                {
                                    pen1 = new Pen(FactionColors[thisFaction.ID], penWidth);
                                    Pen pen2 = new Pen(FactionColors[neighbourFaction.ID], penWidth);
                                    graphics.DrawLineTwoColour(pen1, pen2, p1, p2, 5);
                                }
                            }
                        }
                    }

                    string tileString = "X";
                    Pen    stringPen  = new Pen(Color.Red);
                    Pen    fillPen    = new Pen(Color.ForestGreen);
                    switch (thisTile.Type)
                    {
                    case TerrainTypes.Land:
                        tileString      = " ";
                        stringPen.Brush = Brushes.SandyBrown;
                        break;

                    case TerrainTypes.Water:
                        tileString      = " ";
                        stringPen.Brush = Brushes.Aqua;
                        fillPen.Color   = Color.DeepSkyBlue;
                        break;

                    case TerrainTypes.City:
                        tileString      = "c";
                        stringPen.Brush = Brushes.LightGray;
                        //fillPen.Color=Color.SandyBrown;
                        break;

                    case TerrainTypes.Harbor:
                        tileString      = "H";
                        stringPen.Brush = Brushes.Yellow;
                        break;

                    case TerrainTypes.Capital:
                        tileString      = "C";
                        stringPen.Brush = Brushes.DarkGray;
                        break;

                    default:
                        tileString = "X";
                        break;
                    }

                    RectangleF rect = new RectangleF(centerPointX - hexRadiusX * 0.8f, centerPointY - hexRadiusY * 0.8f, hexRadiusX * 1.6f, hexRadiusY * 1.6f);
                    graphics.FillEllipse(fillPen.Brush, rect);

                    graphics.DrawString(tileString,
                                        new Font(FontFamily.GenericSansSerif, 25), stringPen.Brush, new PointF(centerPointX - 15, centerPointY - 18));


                    graphics.DrawString(tileX.ToString() + ", " + tileY.ToString() + ";" + gameLogicToDraw.GetTile(Tuple.Create(tileX, tileY)).OccupiedByFaction.ID.ToString(),
                                        new Font(FontFamily.GenericMonospace, 7), Brushes.White, new PointF(centerPointX - 20, centerPointY - 7));
                }
            }

            /*GraphicsPath path = new GraphicsPath();
             * GraphicsPath path2 = new GraphicsPath();
             * //Point[] points = new Point[] { new Point(0, 50), new Point(25, 100), new Point(75, 100), new Point(100, 50), new Point(75, 0), new Point(25, 0) };
             *
             * Point point1 = new Point(-50, 50);
             * point1 = m.TransformPoint(point1);
             *
             * Point point2 = new Point(50, -50);
             * point2 = m.TransformPoint(point2);
             *
             * graphics.DrawLineTwoColour(pen1, pen2, point1, point2, 14);*/

            //path.CloseFigure();
        }
Example #51
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="fontFamily"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        private static List <GlyphPolygons> GenerateGlyphs(FontFamily fontFamily, uint size, FontStyle fontStyle)
        {
            List <GlyphPolygons> glyphs = new List <GlyphPolygons>();

            using (Bitmap bitmap = new Bitmap(1, 1))
                using (Graphics g = Graphics.FromImage(bitmap))
                    using (System.Drawing.Font font = new System.Drawing.Font(fontFamily, size, fontStyle))
                        using (GraphicsPath graphicsPath = new GraphicsPath()) {
                            StringFormat stringFormat = StringFormat.GenericTypographic;

                            // Avoid grid fitting
                            g.TextRenderingHint = TextRenderingHint.AntiAlias;

                            System.Drawing.Drawing2D.Matrix gPathMatrix = new System.Drawing.Drawing2D.Matrix();
                            gPathMatrix.Translate(0.0f, size);
                            gPathMatrix.Scale(+1.25f, -1.25f);          // Note: GraphicsPath is currently giving path points smaller than
                            // the equivalent texture font.

                            graphicsPath.FillMode = FillMode.Winding;

                            foreach (char c in GetFontCharacters())
                            {
                                graphicsPath.AddString(c.ToString(), fontFamily, (int)fontStyle, size, new PointF(0, 0), stringFormat);
                                graphicsPath.Flatten();
                                graphicsPath.Transform(gPathMatrix);

                                List <List <Vertex2f> > vCountours = new List <List <Vertex2f> >();

                                try {
                                    PointF[] gPoints    = graphicsPath.PathPoints;
                                    byte[]   gPathTypes = graphicsPath.PathTypes;

                                    List <Vertex2f> vCountour           = null;
                                    int             vCountourStartIndex = 0;

                                    for (int i = 0; i < gPoints.Length; i++)
                                    {
                                        switch (gPathTypes[i] & 0x07)
                                        {
                                        case 0:
                                            vCountour           = new List <Vertex2f>();
                                            vCountourStartIndex = i;
                                            continue;

                                        case 1:
                                            if (vCountour == null)
                                            {
                                                throw new InvalidOperationException("no start point");
                                            }
                                            vCountour.Add(new Vertex2f(gPoints[i].X, gPoints[i].Y));
                                            break;

                                        default:
                                            throw new NotSupportedException();
                                        }

                                        if ((gPathTypes[i] & 0x80) != 0)
                                        {
                                            vCountour.Add(new Vertex2f(gPoints[vCountourStartIndex].X, gPoints[vCountourStartIndex].Y));
                                            vCountours.Add(vCountour);
                                        }
                                    }
                                } catch (Exception) {
                                    vCountours.Clear();
                                }

                                SizeF cSize;

                                switch (c)
                                {
                                case ' ':
                                    cSize = g.MeasureString(c.ToString(), font, 0, StringFormat.GenericDefault);
                                    break;

                                default:
                                    cSize = g.MeasureString(c.ToString(), font, 0, stringFormat);
                                    break;
                                }

                                glyphs.Add(new GlyphPolygons(c, cSize, vCountours));
                                graphicsPath.Reset();
                            }
                        }

            return(glyphs);
        }
Example #52
0
 partial void ScaleImpl(float sx, float sy)
 {
     t.Scale(sx, sy);
 }
Example #53
0
        public void Draw(Graphics g, RectangleF viewport)
        {
            var transform = g.Transform;

            g.SmoothingMode      = SmoothingMode.HighQuality;
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.InterpolationMode  = InterpolationMode.HighQualityBicubic;

            var mat = new Matrix();

            mat.Translate(CurrentProject.Translation.X, CurrentProject.Translation.Y);
            mat.Scale(CurrentProject.Zoom, CurrentProject.Zoom, MatrixOrder.Append);
            g.Transform = mat;

            if (Settings.DrawGrid)
            {
                DrawGrid(g, viewport);
            }

            if (CurrentProject.Ready)
            {
                foreach (var connection in CurrentProject.Connections)
                {
                    var p1 =
                        connection.FromInputOutput.InputOutput.GetTranslationCenter(connection.FromInputOutput.Origin);
                    var p2 = connection.ToInputOutput.InputOutput.GetTranslationCenter(connection.ToInputOutput.Origin);
                    connection.Draw(this, g);

                    //DrawConnection(g, connection.ToInputOutput.InputOutput.Signature.Pen, _linePen, p1, p2);
                }

                if (SelectionService.InputOutputAvailable)
                {
                    var io = SelectionService.SelectedInputOutput;
                    if (io != null)
                    {
                        var p1  = SelectionService.DestinationConnectionPosition;
                        var p2  = io.InputOutput.GetTranslationCenter(io.Origin);
                        var pen = io.InputOutput.Signature.Pen;
                        if (!io.IsInput)
                        {
                            Connection.Draw(this, g, pen, p1, p2);
                        }
                        else
                        {
                            Connection.Draw(this, g, pen, p2, p1);
                        }
                    }
                }

                foreach (var item in CurrentProject.Items)
                {
                    item.Draw(g, this, null);
                }

                foreach (var item in CurrentProject.Items)
                {
                    item.DrawHelp(g, this, null);
                }
            }

            // Translated Rectangle Debug Modus
            //if (MouseService.LeftMouseDown)
            //{
            //    var rect = SelectionService.SelectionRectangleTranslated;
            //    g.DrawRectangle(Pens.DimGray, rect.X, rect.Y, rect.Width, rect.Height);
            //    g.FillRectangle(Brushes.PaleVioletRed, rect);
            //}

            g.Transform = transform;

            // Selection nach Rückgängig machen der Transformation, so ist die Box wieder an der richtigen Position
            DrawSelectionRectangle(g);

            DrawRenderingInfo(g, viewport);
        }
Example #54
0
        private static Bitmap CutImage(Texture2D m_Texture2D, Sprite m_Sprite, RectangleF textureRect, SpriteSettings settingsRaw)
        {
            var texture2D     = new Texture2DConverter(m_Texture2D);
            var originalImage = texture2D.ConvertToBitmap(false);

            if (originalImage != null)
            {
                using (originalImage)
                {
                    var spriteImage = originalImage.Clone(textureRect, PixelFormat.Format32bppArgb);

                    if (settingsRaw.packed == 1)
                    {
                        //RotateAndFlip
                        switch (settingsRaw.packingRotation)
                        {
                        case SpritePackingRotation.kSPRFlipHorizontal:
                            spriteImage.RotateFlip(RotateFlipType.RotateNoneFlipX);
                            break;

                        case SpritePackingRotation.kSPRFlipVertical:
                            spriteImage.RotateFlip(RotateFlipType.RotateNoneFlipY);
                            break;

                        case SpritePackingRotation.kSPRRotate180:
                            spriteImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
                            break;

                        case SpritePackingRotation.kSPRRotate90:
                            spriteImage.RotateFlip(RotateFlipType.Rotate270FlipNone);
                            break;
                        }

                        //Tight
                        //TODO 2017 and up use m_PhysicsShape should be better
                        if (settingsRaw.packingMode == SpritePackingMode.kSPMTight)
                        {
                            try
                            {
                                var triangles = GetTriangles(m_Sprite.m_RD);
                                var points    = triangles.Select(x => x.Select(y => new PointF(y.X, y.Y)).ToArray());
                                using (var path = new GraphicsPath())
                                {
                                    foreach (var p in points)
                                    {
                                        path.AddPolygon(p);
                                    }
                                    using (var matr = new System.Drawing.Drawing2D.Matrix())
                                    {
                                        if (m_Sprite.m_Pivot == Vector2.Zero) //5.4.2 down
                                        {
                                            matr.Translate(m_Sprite.m_Rect.Width * 0.5f, m_Sprite.m_Rect.Height * 0.5f);
                                        }
                                        else
                                        {
                                            matr.Translate(m_Sprite.m_Rect.Width * m_Sprite.m_Pivot.X, m_Sprite.m_Rect.Height * m_Sprite.m_Pivot.Y);
                                        }
                                        matr.Scale(m_Sprite.m_PixelsToUnits, m_Sprite.m_PixelsToUnits);
                                        path.Transform(matr);
                                        var bitmap = new Bitmap((int)textureRect.Width, (int)textureRect.Height);
                                        using (var graphic = Graphics.FromImage(bitmap))
                                        {
                                            using (var brush = new TextureBrush(spriteImage))
                                            {
                                                graphic.FillPath(brush, path);
                                                bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
                                                return(bitmap);
                                            }
                                        }
                                    }
                                }
                            }
                            catch
                            {
                                // ignored
                            }
                        }
                    }

                    //Rectangle
                    spriteImage.RotateFlip(RotateFlipType.RotateNoneFlipY);
                    return(spriteImage);
                }
            }

            return(null);
        }
Example #55
0
        private InPage GetInputPage(byte[] imageData, string regionData, string ocrchardata)
        {
            InPage page = new InPage(imageData);


            #region regiondataparsing
            string[] splitter1      = { "\r\n" };
            string[] splitter2      = { "#" };
            string[] splitter3      = { ";" };
            var      splittedRegion = regionData.Split(splitter1, StringSplitOptions.RemoveEmptyEntries);
            foreach (var splitted in splittedRegion)
            {
                var    splittedTemp = splitted.Split(splitter2, StringSplitOptions.RemoveEmptyEntries);
                string number       = splittedTemp[0];
                string type         = splittedTemp[1];
                Zone   zone         = new Zone();
                zone.Type   = ParseZoneType(type);
                zone.Number = Int32.Parse(number);
                GraphicsPath path          = new GraphicsPath();
                string[]     splittedRects = splittedTemp[2].Split(splitter3, StringSplitOptions.RemoveEmptyEntries);

                for (int i = 0; i < splittedRects.Length; i += 4)
                {
                    string x = splittedRects[i].Replace(",", ".");
                    string y = splittedRects[i + 1].Replace(",", ".");
                    string w = splittedRects[i + 2].Replace(",", ".");
                    string h = splittedRects[i + 3].Replace(",", ".");

                    path.AddRectangle(new RectangleF(float.Parse(x, CultureInfo.InvariantCulture), float.Parse(y, CultureInfo.InvariantCulture), float.Parse(w, CultureInfo.InvariantCulture), float.Parse(h, CultureInfo.InvariantCulture)));
                }
                Region reg = new Region(path);

                Matrix transformMatrix = new Matrix();
                transformMatrix.Scale(page.Img.HorizontalResolution / 200, page.Img.VerticalResolution / 200);
                reg.Transform(transformMatrix);

                path.Dispose();
                zone.Reg = reg;

                page.Zones.Add(zone);
            }
            #endregion

            #region ocrdataparsing


            float    scale           = page.Img.HorizontalResolution / 200f;
            string[] splitera1       = { "\r\n" };
            string[] splittera2      = { ";" };
            string[] splittedocrchar = ocrchardata.Split(splitera1, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 1; i < splittedocrchar.Length; ++i)
            {
                var temp       = splittedocrchar[i].Split(splittera2, StringSplitOptions.RemoveEmptyEntries);
                int zonenumber = int.Parse(temp[0]);

                string indexnumber = temp[2];
                for (int ia = 5; ia < temp.Length; ia += 4)
                {
                    float left   = float.Parse(temp[ia].Replace(",", "."), CultureInfo.InvariantCulture);
                    float right  = float.Parse(temp[ia + 1].Replace(",", "."), CultureInfo.InvariantCulture);
                    float bottom = float.Parse(temp[ia + 2].Replace(",", "."), CultureInfo.InvariantCulture);
                    float top    = float.Parse(temp[ia + 3].Replace(",", "."), CultureInfo.InvariantCulture);


                    //float zoneLeft = (float.Parse(temp[ia].Replace(",", "."), CultureInfo.InvariantCulture))-page.Zones[zonenumber].Reg.GetBounds(grp).Left;
                    //float zoneRight = (float.Parse(temp[ia + 1].Replace(",", "."), CultureInfo.InvariantCulture)) - page.Zones[zonenumber].Reg.GetBounds(grp).X;
                    //float zoneBottom = (float.Parse(temp[ia + 2].Replace(",", "."), CultureInfo.InvariantCulture))- page.Zones[zonenumber].Reg.GetBounds(grp).Bottom;
                    //float zoneTop = (float.Parse(temp[ia + 3].Replace(",", "."), CultureInfo.InvariantCulture))-page.Zones[zonenumber].Reg.GetBounds(grp).Y;


                    RectangleF rect = new RectangleF(left * scale, top * scale, (right - left) * scale, (bottom - top) * scale);

                    // RectangleF zoneRect=new RectangleF((left * scale)-zoneX , (top * scale)-zoneY, ((right - left) * scale), ((bottom - top) * scale));

                    Character character = new Character();
                    character.Rect = rect;

                    character.Index = int.Parse(indexnumber);

                    page.Zones.Where(p => p.Number == zonenumber).First().Chars.Add(character);
                }
            }
            #endregion



            return(page);
        }
Example #56
0
        public void Draw(IGraphics gr, float scale, int selectedEdit, int selectedEditTL, Point Translate, bool Clips, int width)
        {
            System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix();
            m.Translate(Translate.X, Translate.Y);
            m.Scale(scale, scale, System.Drawing.Drawing2D.MatrixOrder.Append);
            gr.Transform = m;

            for (int i = 0; i < timelines.Count; i++)
            {
                timelines[i].Draw(gr, -Translate.X, -Translate.X + width);
                if (selectedEditTL == i)
                {
                    gr.FillEllipse(Brushes.Red, new Rectangle((int)-Translate.X + 5, timelines[i].Ylocation - 5, 4, 4));
                }
            }

            int minx = int.MaxValue, miny = int.MaxValue, maxx = int.MinValue, maxy = int.MinValue;
            int maxtext = 0;

            // connections
            for (int i = 0; i < phrases.Count; i++)
            {
                phrases[i].DrawConnections(gr, this);
                // clips
                phrases[i].DrawGClip(gr, Clips);
            }
            // ovals
            for (int i = 0; i < phrases.Count; i++)
            {
                phrases[i].DrawOval(gr);
            }
            for (int i = 0; i < phrases.Count; i++)
            {
                maxtext = phrases[i].MeasuredLabel == SizeF.Empty ? (int)gr.MeasureString(phrases[i].Label, DRes.useFont).Width : (int)phrases[i].MeasuredLabel.Width;
                minx    = Math.Min(minx, phrases[i].locationC.X - maxtext);
                miny    = Math.Min(miny, phrases[i].locationC.Y);
                SizeF tm = phrases[i].MeasuredText == SizeF.Empty ? gr.MeasureString(phrases[i].ShortText, DRes.useFont) : phrases[i].MeasuredText;
                maxtext = (int)tm.Width; //phrases[i].MeasuredText = tm;

                maxx = Math.Max(maxx, phrases[i].locationC.X + maxtext);
                maxy = Math.Max(maxy, phrases[i].locationC.Y);

                if (Clips && phrases[i].GraphicClipThumbnail != null)
                {
                    Rectangle grrect = phrases[i].GraphicClipRectangle;
                    maxx = Math.Max(maxx, grrect.Right);
                    maxy = Math.Max(maxy, grrect.Bottom);

                    minx = Math.Min(minx, grrect.Left);
                    miny = Math.Min(miny, grrect.Top);
                }
                //phrases[i].DrawConnections(gr, this);
                phrases[i].Draw(gr);

                if (selectedEdit == i)
                {
                    gr.FillEllipse(Brushes.Red, new Rectangle(phrases[i].locationC.X - 2, phrases[i].locationC.Y - 2, 4, 4));
                }
            }
            if (phrases.Count != 0)
            {
                VisibleRange[0].X = minx - 12; VisibleRange[0].Y = miny - 12;
                VisibleRange[1].X = maxx + 12; VisibleRange[1].Y = maxy + 16;
                gr.DrawRectangle(Pens.Aqua, VisibleRect);
            }
        }
        /// <summary>
        /// Creates an image that shows the effector graph for the given control points.
        /// </summary>
        /// <param name="controlPoints">The control points for the effector.</param>
        /// <returns></returns>
        public Bitmap getEffectorImage(PointF[] controlPoints)
        {
            // DEBUG
            //return new Bitmap(@"C:\Users\evans\Pictures\Icon Images\BlueMouse.256x256.png");
            int    margin = 10;
            int    w = 256, h = w;
            float  scale = w - 2 * margin;
            Bitmap bm    = new Bitmap(w, h);
            // RTfUtils uses this to set the size
            float sizeInches = 1.0f;

            bm.SetResolution(w / sizeInches, h / sizeInches);
            using (Graphics g = Graphics.FromImage(bm)) {
                // Scale it so we can work in [0,1] coordinate axes,
                // with y increasing up
                Matrix m = new System.Drawing.Drawing2D.Matrix();
                m.Scale(1f, -1f);
                m.Translate(0, -h);
                m.Translate(margin, margin);
                m.Scale(scale, scale);
                g.Transform = m;
                g.Clear(Color.FromArgb(191, 191, 191));
                // Grid lines
                using (Pen pen = new Pen(Color.White, 1 / scale)) {
                    for (int i = 1; i < 4; i++)
                    {
                        g.DrawLine(pen, .25f * i, 0, .25f * i, 1);
                        g.DrawLine(pen, 0, .25f * i, 1, .25f * i);
                    }
                }
                // Axes
                using (Pen pen = new Pen(Color.Black, 1 / scale)) {
                    g.DrawLine(pen, 0, 0, 1, 0);
                    g.DrawLine(pen, 1, 0, 1, 1);
                    g.DrawLine(pen, 1, 1, 0, 1);
                    g.DrawLine(pen, 0, 1, 0, 0);
                }
                // Control points
                using (Brush brush = new SolidBrush(Color.FromArgb(140, 152, 252))) {
                    int width = 9;  // Should be odd
                    int off   = (width - 1) / 2;
                    foreach (PointF point in controlPoints)
                    {
                        g.FillRectangle(brush,
                                        new RectangleF(point.X - off / scale, point.Y - off / scale,
                                                       width / scale, width / scale));
                    }
                }
                // Control point lines
                using (Pen pen = new Pen(Color.FromArgb(140, 152, 252), 2 / scale)) {
                    float xPrev = controlPoints[0].X;
                    float yPrev = controlPoints[0].Y;
                    for (int i = 1; i < controlPoints.Length; i++)
                    {
                        g.DrawLine(pen, xPrev, yPrev, controlPoints[i].X, controlPoints[i].Y);
                        xPrev = controlPoints[i].X;
                        yPrev = controlPoints[i].Y;
                    }
                }
                // Curves
                PointF[] ccp;
                using (Pen pen = new Pen(Color.Black, 2 / scale)) {
                    int nPoints = controlPoints.Length;
                    if (nPoints == 2)
                    {
                        g.DrawLine(pen, controlPoints[0], controlPoints[1]);
                    }
                    else if (nPoints == 3)
                    {
                        ccp = cubicBezier(controlPoints[0], controlPoints[1], controlPoints[2]);
                        g.DrawBezier(pen, ccp[0], ccp[1], ccp[2], ccp[3]);
                    }
                    else if (nPoints > 3)
                    {
                        // First
                        ccp = cubicBezier(controlPoints[0], controlPoints[1],
                                          midpoint(controlPoints[1], controlPoints[2]));
                        g.DrawBezier(pen, ccp[0], ccp[1], ccp[2], ccp[3]);
                        // Middle
                        for (int i = 2; i < nPoints - 2; i++)
                        {
                            ccp = cubicBezier(midpoint(controlPoints[i - 1], controlPoints[i]),
                                              controlPoints[i],
                                              midpoint(controlPoints[i], controlPoints[i + 1]));
                            g.DrawBezier(pen, ccp[0], ccp[1], ccp[2], ccp[3]);
                        }
                        // Last
                        ccp = cubicBezier(midpoint(controlPoints[nPoints - 3], controlPoints[nPoints - 2]),
                                          controlPoints[nPoints - 2],
                                          controlPoints[nPoints - 1]);
                        g.DrawBezier(pen, ccp[0], ccp[1], ccp[2], ccp[3]);
                    }
                }
            }
            bm.Save(@"C:\Scratch\AAA\" + name + "TestDocument.png", ImageFormat.Png);
            return(bm);
        }
Example #58
0
        /// <summary>
        /// Without this change, labels render upside down and don't all scale readably.
        /// </summary>
        /// <param name="g"></param>
        /// <param name="ro"></param>
        /// <returns></returns>
        protected RectangleF AdjustForLabel(Graphics g, GdiRenderObject ro)
        {
            // this transform goes from the underlying coordinates to
            // screen coordinates, but for some reason renders text upside down
            // we cannot just scale by 1, -1 because offsets are affected also
            GdiMatrix m = g.Transform;
            // used to scale text size for the current zoom level
            float scale = Math.Abs(m.Elements[0]);

            // get the bounds of the label in the underlying coordinate space
            Point ll = new Point((Int32)ro.Bounds.X, (Int32)ro.Bounds.Y);
            Point ur = new Point((Int32)(ro.Bounds.X + ro.Bounds.Width),
                                 (Int32)(ro.Bounds.Y + ro.Bounds.Height));

            Point[] transformedPoints1 =
            {
                new Point((Int32)ro.Bounds.X,                     (Int32)ro.Bounds.Y),
                new Point((Int32)(ro.Bounds.X + ro.Bounds.Width),
                          (Int32)(ro.Bounds.Y + ro.Bounds.Height))
            };

            // get the label bounds transformed into screen coordinates
            // note that if we just render this as-is the label is upside down
            m.TransformPoints(transformedPoints1);

            // for labels, we're going to use an identity matrix and screen coordinates
            GdiMatrix newM = new GdiMatrix();

            Boolean scaleText = true;

            /*
             *          if (ro.Layer != null)
             *          {
             *              Double min = ro.Layer.Style.MinVisible;
             *              Double max = ro.Layer.Style.MaxVisible;
             *              float scaleMult = Double.IsInfinity(max) ? 2.0f : 1.0f;
             *
             *              //max = Math.Min(max, _presenter.MaximumWorldWidth);
             *              max = Math.Min(max, Map.Extents.Width);
             *              //Double pct = (max - _presenter.WorldWidth) / (max - min);
             *              Double pct = 1 - (Math.Min(_presenter.WorldWidth, Map.Extents.Width) - min) / (max - min);
             *
             *              if (scaleMult > 1)
             *              {
             *                  pct = Math.Max(.5, pct * 2);
             *              }
             *
             *              scale = (float)pct*scaleMult;
             *              labelScale = scale;
             *          }
             */

            // ok, I lied, if we're scaling labels we need to scale our new matrix, but still no offsets
            if (scaleText)
            {
                newM.Scale(scale, scale);
            }
            else
            {
                scale = 1.0f;
            }

            g.Transform = newM;

            Int32 pixelWidth  = ur.X - ll.X;
            Int32 pixelHeight = ur.Y - ll.Y;

            // if we're scaling text, then x,y position will get multiplied by our
            // scale, so adjust for it here so that we can use actual pixel x,y
            // Also center our label on the coordinate instead of putting the label origin on the coordinate
            RectangleF newBounds = new RectangleF(transformedPoints1[0].X / scale,
                                                  (transformedPoints1[0].Y / scale) - pixelHeight,
                                                  pixelWidth,
                                                  pixelHeight);

            //RectangleF newBounds = new RectangleF(transformedPoints1[0].X / scale - (pixelWidth / 2), transformedPoints1[0].Y / scale - (pixelHeight / 2), pixelWidth, pixelHeight);

            return(newBounds);
        }
Example #59
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 #60
0
        public void DrawSketch(Graphics g, float zoom, bool show_idx, bool colored)         //g: Bitmap坐标系
        {
            int W = (int)Math.Ceiling(maxx * zoom);
            int H = (int)Math.Ceiling(maxy * zoom);

            using (Brush brush = new SolidBrush(Color.Black))
                g.FillRectangle(brush, new Rectangle(0, 0, W + 1, H + 1));                 //必须+1

            //从显示拓扑坐标系(笛卡尔)->Bmp设备坐标系
            Matrix2D trans = new Matrix2D(1, 0, 0, -1, 0, maxy);             //Y翻转

            trans.Scale(zoom, zoom, MatrixOrder.Append);                     //再缩放
            g.Transform = trans;

            //绘制所有多边形,根据属性着色
            if (colored)
            {
                for (int i = 0; i < num_polys; i++)
                {
                    DrawColoredPolygon(g, polys[i]);
                }
            }

            using (Pen pen = new Pen(Color.FromArgb(150, Color.Red)))
            {
                for (int i = 0; i < num_borders; i++)
                {
                    FPoint from = borders[i].from;
                    FPoint to   = borders[i].to;
                    g.DrawLine(pen, from.x, from.y, to.x, to.y);
                }
            }

            using (Pen pen = new Pen(Color.White))
            {
                for (int i = 0; i < num_polys; i++)
                {
                    if (!polys[i].enterable)
                    {
                        Polygon p = polys[i];
                        for (int j = 0; j < p.num_borders; j++)
                        {
                            FPoint from = p.borders[j].from;
                            FPoint to   = p.borders[j].to;
                            g.DrawLine(pen, from.x, from.y, to.x, to.y);
                        }
                    }
                }
            }

            //------------------------------------------------------------------------
            if (show_idx)
            {
                g.ResetTransform();

                using (Font font = new Font("Tahoma", 8.5F * zoom))
                    using (Brush brush = new SolidBrush(Color.White))
                    {
                        PointF[] pos = { new PointF(0, 0) };
                        for (int i = 0; i < num_polys; i++)
                        {
                            FPoint fp = polys[i].GetCentroid();

                            pos[0].X = fp.x;
                            pos[0].Y = fp.y;

                            //从显示拓扑坐标系->Bmp设备坐标系
                            trans.TransformPoints(pos);

                            SizeF size = g.MeasureString(i.ToString(), font);
                            pos[0].X -= size.Width / 2;
                            pos[0].Y -= size.Height / 2;

                            g.DrawString(i.ToString(), font, brush, pos[0]);
                        }
                    }
            }
        }