Translate() публичный Метод

public Translate ( float offsetX, float offsetY ) : void
offsetX float
offsetY float
Результат void
        public static void Run()
        {
            // ExStart:CalculateCenterOfSubShapes
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_Shapes();

            // Load Visio diagram
            Diagram diagram = new Diagram(dataDir + "Drawing1.vsdx");
            // Get a group shape by ID and page index is 0
            Shape shape = diagram.Pages[0].Shapes.GetShape(795);
            // Get a sub-shape of the group shape by id
            Shape subShape = shape.Shapes.GetShape(794);

            Matrix m = new Matrix();
            // Apply the translation vector
            m.Translate(-(float)subShape.XForm.LocPinX.Value, -(float)subShape.XForm.LocPinY.Value);
            // Set the elements of that matrix to a rotation
            m.Rotate((float)subShape.XForm.Angle.Value);
            // Apply the translation vector
            m.Translate((float)subShape.XForm.PinX.Value, (float)subShape.XForm.PinY.Value);

            // Get pinx and piny
            double pinx = m.OffsetX;
            double piny = m.OffsetY;
            // Calculate the sub-shape pinx and piny
            double resultx = shape.XForm.PinX.Value - shape.XForm.LocPinX.Value - pinx;
            double resulty = shape.XForm.PinY.Value - shape.XForm.LocPinY.Value - piny;
            // ExEnd:CalculateCenterOfSubShapes
        }
Пример #2
0
        public override void DrawEffectImage(Bitmap current, Bitmap next, EffectingPanel effecingPanel)
        {
            int step = 1;
            Graphics bg;
            Bitmap doubleBufferingBitmap;
            SolidBrush solidBrush;
            Rectangle rectangle;
            Matrix matrix = null;

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

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

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

                ResetInterval();

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

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

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

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

                    DoEventAtIntervals();
                }

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

                effecingPanel.pictureBox.Image = next;
            }
            catch (SystemException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
 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();
 }
Пример #4
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)
                             };
        }
Пример #5
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;
		}
Пример #6
0
 /*
  * Translate
  * методът се ползва при скалиране
  * за нулиране на нежелан ефект при скалирнаето(изместване на фигурата в страни)
  * и за нормално транслиране - преместване
  * **/
 public virtual void Translate(float X,float Y)
 {
     Matrix tempMatrix = new Matrix();
     tempMatrix.Translate(X, Y);
     tempMatrix.Multiply(TransformationMatrix);
     TransformationMatrix = tempMatrix;
 }
Пример #7
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);
        }
Пример #8
0
        public static Image ApplyRegionPathToImage(Image backgroundImage, GraphicsPath regionFillPath, RegionCaptureOptions options)
        {
            if (backgroundImage != null && regionFillPath != null)
            {
                Image img;

                Rectangle regionArea = Rectangle.Round(regionFillPath.GetBounds());
                Rectangle screenRectangle = CaptureHelpers.GetScreenBounds0Based();
                Rectangle newRegionArea = Rectangle.Intersect(regionArea, screenRectangle);

                using (GraphicsPath gp = (GraphicsPath)regionFillPath.Clone())
                {
                    using (Matrix matrix = new Matrix())
                    {
                        gp.CloseFigure();
                        matrix.Translate(-Math.Max(0, regionArea.X), -Math.Max(0, regionArea.Y));
                        gp.Transform(matrix);
                    }

                    img = ImageHelpers.CropImage(backgroundImage, newRegionArea, gp);
                }

                return img;
            }

            return null;
        }
Пример #9
0
        public static Bitmap CropRotatedRect(Bitmap source, System.Drawing.Rectangle rect, float angle, bool HighQuality)

        {
            Bitmap result = new Bitmap(rect.Width, rect.Height);

            using (Graphics g = Graphics.FromImage(result))

            {
                g.InterpolationMode = HighQuality ? InterpolationMode.HighQualityBicubic : InterpolationMode.Default;

                using (System.Drawing.Drawing2D.Matrix mat = new System.Drawing.Drawing2D.Matrix())

                {
                    mat.Translate(-rect.Location.X, -rect.Location.Y);

                    System.Drawing.Point p = new System.Drawing.Point(rect.Location.X + rect.Width / 2, rect.Location.Y + rect.Height / 2);

                    mat.RotateAt(angle, p);

                    g.Transform = mat;

                    g.DrawImage(source, new System.Drawing.Point(0, 0));
                }
            }

            return(result);
        }
Пример #10
0
        /// <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;
        }
Пример #11
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);
            }

        }
Пример #12
0
        public static Image FlipImage(Image image, bool flipHorizontally, bool flipVertically)
        {
            Bitmap flippedImage = new Bitmap(image.Width, image.Height);

            using (Graphics g = Graphics.FromImage(flippedImage))
            {
                //Matrix transformation
                Matrix m = null;
                if (flipVertically && flipHorizontally)
                {
                    m = new Matrix(-1, 0, 0, -1, 0, 0);
                    m.Translate(flippedImage.Width, flippedImage.Height, MatrixOrder.Append);
                }
                else if (flipVertically)
                {
                    m = new Matrix(1, 0, 0, -1, 0, 0);
                    m.Translate(0, flippedImage.Height, MatrixOrder.Append);
                }
                else if (flipHorizontally)
                {
                    m = new Matrix(-1, 0, 0, 1, 0, 0);
                    m.Translate(flippedImage.Width, 0, MatrixOrder.Append);
                }

                //Draw
                g.Transform = m;
                g.DrawImage(image, 0, 0);

                //clean up
                m.Dispose();
            }

            return (Image)flippedImage;
        }
Пример #13
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);
        }
Пример #14
0
 public static Bitmap RotateImage(Image inputImg, double degreeAngle)
 {
     PointF[] pointF = new PointF[] { new PointF(0f, 0f), new PointF((float)inputImg.Width, 0f), new PointF(0f, (float)inputImg.Height), new PointF((float)inputImg.Width, (float)inputImg.Height) };
     PointF[] rotationPoints = pointF;
     PointMath.RotatePoints(rotationPoints, new PointF((float)inputImg.Width / 2f, (float)inputImg.Height / 2f), degreeAngle);
     Rectangle bounds = PointMath.GetBounds(rotationPoints);
     Bitmap rotatedBitmap = new Bitmap(bounds.Width, bounds.Height);
     Graphics g = Graphics.FromImage(rotatedBitmap);
     try
     {
         g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
         g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
         Matrix m = new Matrix();
         m.RotateAt((float)degreeAngle, new PointF((float)inputImg.Width / 2f, (float)inputImg.Height / 2f));
         m.Translate((float)(-bounds.Left), (float)(-bounds.Top), MatrixOrder.Append);
         g.Transform = m;
         g.DrawImage(inputImg, 0, 0);
     }
     finally
     {
         if (g != null)
         {
             ((IDisposable)g).Dispose();
         }
     }
     return rotatedBitmap;
 }
Пример #15
0
        protected override void OnPaint(PaintEventArgs e)
        {
            if (backBuffer == null)
                backBuffer = new Bitmap(this.ClientSize.Width, this.ClientSize.Height);

            Graphics g = doubleBuffering ? Graphics.FromImage(backBuffer) : e.Graphics;

            g.SmoothingMode = smoothing ? SmoothingMode.AntiAlias : SmoothingMode.Default;

            g.Clear(SystemColors.Control);

            Matrix mx = new Matrix();
            mx.Rotate(angle);
            mx.Translate(this.ClientSize.Width / 2, this.ClientSize.Height / 2, MatrixOrder.Append);
            g.Transform = mx;
            g.FillRectangle(Brushes.Red, -100, -100, 200, 200);

            mx = new Matrix();
            mx.Rotate(-angle);
            mx.Translate(this.ClientSize.Width / 2, this.ClientSize.Height / 2, MatrixOrder.Append);
            g.Transform = mx;
            g.FillRectangle(Brushes.Green, -75, -75, 150, 150);

            mx = new Matrix();
            mx.Rotate(angle * 2);
            mx.Translate(this.ClientSize.Width / 2, this.ClientSize.Height / 2, MatrixOrder.Append);
            g.Transform = mx;
            g.FillRectangle(Brushes.Blue, -50, -50, 100, 100);

            if (doubleBuffering)
            {
                g.Dispose();
                e.Graphics.DrawImageUnscaled(backBuffer, 0, 0);
            }
        }
Пример #16
0
    /// <summary>
    /// Applies matrix transformation to graphics
    /// </summary>
    private static void TransformCoordinates()
    {
        using (var bitmap = new Bitmap(600, 300, PixelFormat.Format24bppRgb, RgbColor.White))
            using (var graphics = bitmap.GetAdvancedGraphics())
            {
                // Move coordinate system
                var matrix1 = new System.Drawing.Drawing2D.Matrix();
                matrix1.Translate(bitmap.Width / 2, bitmap.Height / 2);

                graphics.Transform = matrix1;

                DrawEllipseAndText(graphics, 30);

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

                graphics.Transform = matrix2;

                DrawEllipseAndText(graphics, 255);

                bitmap.Save("../../../../_Output/TransformCoordinates.png");
            }
    }
Пример #17
0
        public Image GetCroppedScreenshot()
        {
            using (Graphics g = Graphics.FromImage(Screenshot))
            {
                Region region = Manager.CombineAreas();

                if (!region.IsEmpty(g))
                {
                    RectangleF rect = region.GetBounds(g);
                    Bitmap bmp = new Bitmap((int)rect.Width, (int)rect.Height);

                    using (Graphics g2 = Graphics.FromImage(bmp))
                    {
                        g2.Clear(Color.Transparent);

                        using (Matrix translateMatrix = new Matrix())
                        {
                            translateMatrix.Translate(-rect.X, -rect.Y);
                            region.Transform(translateMatrix);
                        }

                        g2.IntersectClip(region);

                        g2.CompositingQuality = CompositingQuality.HighQuality;
                        g2.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        g2.DrawImage(Screenshot, new Rectangle(0, 0, bmp.Width, bmp.Height), rect, GraphicsUnit.Pixel);

                        return bmp;
                    }
                }
            }

            return null;
        }
Пример #18
0
        private Pipeline GetAlphaChannel(float dpi, IEnumerable <IDisposable> deps)
        {
            var image = Content as ImageVObject;

            if (image == null)
            {
                return(null);
            }

            var rect = image.GetDrawingRectangle(dpi);

            var clippingPath = GetClippingPath(dpi);

            using (var matrix = new Matrix())
            {
                rect.Angle = 0;
                matrix.RotateAt(-(float)image.Angle, rect.Center.ToPointF(), MatrixOrder.Append);
                matrix.Translate(-rect.Location.X, -rect.Location.Y, MatrixOrder.Append);
                clippingPath.ApplyTransform(matrix);
            }

            ((IList)deps).Add(clippingPath);

            var imageGenerator = new ImageGenerator((int)rect.Width, (int)rect.Height, PixelFormat.Format8bppGrayscale, RgbColor.Black);
            var drawer         = new Drawer();

            drawer.Draw += (sender, e) =>
            {
                e.Graphics.FillPath(new SolidBrush(RgbColor.White), clippingPath);
            };

            return(new Pipeline(imageGenerator + drawer));
        }
Пример #19
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);
            }
        }
Пример #20
0
        /// <summary>
        /// Draw Function.</summary>
        /// <param name="g">Graphics for Drawing</param>
        public void Draw(Graphics g, float rollAngle, float pitchAngle)
        {
            Matrix transformMatrix = new Matrix();
            transformMatrix.RotateAt(rollAngle, center);
            transformMatrix.Translate(0, pitchAngle * pixelPerDegree);

            // Previous major graduation value next to currentValue.
            int majorGraduationValue = ((int)(pitchAngle / 10) * 10);

            for (int degree = majorGraduationValue - 20; degree <= majorGraduationValue + 20; degree += 5)
            {
                if (degree == 0)
                    continue;

                int width = degree % 10 == 0 ? 60 : 30;

                GraphicsPath skyPath = new GraphicsPath();

                skyPath.AddLine(center.X - width, center.Y - degree * pixelPerDegree, center.X + width, center.Y - degree * pixelPerDegree);
                skyPath.Transform(transformMatrix);
                g.DrawPath(drawingPen, skyPath);

                //g.DrawString(degree.ToString(), SystemFonts.DefaultFont, Brushes.White, center.X - width - 15, center.Y - degree * 10);
            }
        }
Пример #21
0
        // Hack function to to diaonal flip first in transformations first
        static public void TransformPoints_DiagFirst(PointF[] points, PointF origin, bool diagonal, bool horizontal, bool vertical)
        {
            Matrix translate = new Matrix();
            Matrix rotate = new Matrix();

            // Put the points into origin/local space
            translate.Translate(-origin.X, -origin.Y);
            translate.TransformPoints(points);

            // Apply the flips/rotations
            if (diagonal)
            {
                Matrix d = new Matrix(0, 1, 1, 0, 0, 0);
                rotate.Multiply(d);
            }
            if (horizontal)
            {
                Matrix h = new Matrix(-1, 0, 0, 1, 0, 0);
                rotate.Multiply(h);
            }
            if (vertical)
            {
                Matrix v = new Matrix(1, 0, 0, -1, 0, 0);
                rotate.Multiply(v);
            }

            // Apply the combined flip/rotate transformation
            rotate.TransformPoints(points);

            // Put points back into world space
            translate.Invert();
            translate.TransformPoints(points);
        }
Пример #22
0
        public static Bitmap RotateImage(Image img, float theta)
        {
            Matrix matrix = new Matrix();
            matrix.Translate(img.Width / -2, img.Height / -2, MatrixOrder.Append);
            matrix.RotateAt(theta, new Point(0, 0), MatrixOrder.Append);
            using (GraphicsPath gp = new GraphicsPath())
            {
                gp.AddPolygon(new Point[] { new Point(0, 0), new Point(img.Width, 0), new Point(0, img.Height) });
                gp.Transform(matrix);
                PointF[] pts = gp.PathPoints;

                Rectangle bbox = BoundingBox(img, matrix);
                Bitmap bmpDest = new Bitmap(bbox.Width, bbox.Height);

                using (Graphics gDest = Graphics.FromImage(bmpDest))
                {
                    Matrix mDest = new Matrix();
                    mDest.Translate(bmpDest.Width / 2, bmpDest.Height / 2, MatrixOrder.Append);
                    gDest.Transform = mDest;
                    gDest.CompositingQuality = CompositingQuality.HighQuality;
                    gDest.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    gDest.DrawImage(img, pts);
                    return bmpDest;
                }
            }
        }
        public void TranslateTransform(float p1, float p2)
        {
            System.Drawing.Drawing2D.Matrix M2 = new System.Drawing.Drawing2D.Matrix();
            M2.Translate(p1, p2);

            DoTransform(M2);
        }
 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>
        /// On Paint only paints the specified clip rectangle, but paints
        /// it from the page buffer.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPaint(PaintEventArgs e)
        {
            Rectangle clip = e.ClipRectangle;

            if (clip.IsEmpty)
            {
                clip = ClientRectangle;
            }
            if (IsInitialized == false || _page == null)
            {
                Initialize(); // redraw the entire page buffer if necessary
            }

            Bitmap   buffer = new Bitmap(clip.Width, clip.Height);
            Graphics g      = Graphics.FromImage(buffer);

            System.Drawing.Drawing2D.Matrix mat = new System.Drawing.Drawing2D.Matrix();
            mat.Translate(-clip.X, -clip.Y); // draw in "client" coordinates
            g.Transform = mat;

            OnDraw(new PaintEventArgs(g, clip)); // draw content to the small temporary buffer.

            g.Dispose();
            e.Graphics.DrawImage(buffer, clip); // draw from our small, temporary buffer to the screen
            buffer.Dispose();
        }
Пример #26
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;
		}
Пример #27
0
        /// <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);
        }
Пример #28
0
        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);
        }
    /// <summary>
    /// Creates translate matrix
    /// </summary>
    static private Matrix CreateTranslateMatrix(float dx, float dy)
    {
        var translate = new Matrix();

        translate.Translate(dx, dy);

        return(translate);
    }
Пример #30
0
 private static void MoveGraphicsPath(GraphicsPath gp, int x, int y)
 {
     using (Matrix matrix = new Matrix())
     {
         gp.CloseFigure();
         matrix.Translate(x, y);
         gp.Transform(matrix);
     }
 }
Пример #31
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();
        }
        public override Bitmap Build(string text)
        {
            var random = new Random();
            var bitmap = new Bitmap
                (Width, Height, PixelFormat.Format32bppArgb);
            Graphics g = Graphics.FromImage(bitmap);
            g.SmoothingMode = SmoothingMode.AntiAlias;
            var rect = new Rectangle(0, 0, Width, Height);
            var hatchBrush = new HatchBrush(HatchStyle.SmallConfetti,
                Color.LightGray, Color.White);
            g.FillRectangle(hatchBrush, rect);
            SizeF size;
            float fontSize = rect.Height + 1;
            Font font;

            do
            {
                fontSize--;
                font = new Font(FontFamily.GenericSansSerif, fontSize, FontStyle.Bold);
                size = g.MeasureString(text, font);
            } while (size.Width > rect.Width);
            var format = new StringFormat {Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center};
            var path = new GraphicsPath();
            //path.AddString(this.text, font.FontFamily, (int) font.Style,
            //    font.Size, rect, format);
            path.AddString(text, font.FontFamily, (int) font.Style, 75, rect, format);
            float v = 4F;
            PointF[] points =
            {
                new PointF(random.Next(rect.Width)/v, random.Next(
                    rect.Height)/v),
                new PointF(rect.Width - random.Next(rect.Width)/v,
                    random.Next(rect.Height)/v),
                new PointF(random.Next(rect.Width)/v,
                    rect.Height - random.Next(rect.Height)/v),
                new PointF(rect.Width - random.Next(rect.Width)/v,
                    rect.Height - random.Next(rect.Height)/v)
            };
            var matrix = new Matrix();
            matrix.Translate(0F, 0F);
            path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);
            hatchBrush = new HatchBrush(HatchStyle.Percent10, Color.Black, Color.SkyBlue);
            g.FillPath(hatchBrush, path);
            int m = Math.Max(rect.Width, rect.Height);
            for (int i = 0; i < (int) (rect.Width*rect.Height/30F); i++)
            {
                int x = random.Next(rect.Width);
                int y = random.Next(rect.Height);
                int w = random.Next(m/50);
                int h = random.Next(m/50);
                g.FillEllipse(hatchBrush, x, y, w, h);
            }
            font.Dispose();
            hatchBrush.Dispose();
            g.Dispose();
            return bitmap;
        }
Пример #33
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);
        }
Пример #34
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();
        }
Пример #35
0
 public override void ApplyTransformation(System.Drawing.Drawing2D.Matrix transform)
 {
     if (stayCount != 0)
     {
         stayCount--;
         return;
     }
     transform.Translate(toX - fromX, toY - fromY);
     isEnd = true;
 }
Пример #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);
                }
            }
        }
        void Parent_PCBIFormGraphicPaneDrawing(Graphics g, int ClientWidth, int ClientHeight)
        {
            if (!parent.JobIsLoaded)
            {
                return;
            }
            int   pcbCount  = 0;
            IStep PanelStep = parent.GetCurrentStep();

            if (PanelStep == null)
            {
                return;
            }

            RectangleF PanelSize = PanelStep.GetBounds();

            if (PanelSize == RectangleF.Empty)
            {
                return;
            }
            DrawSingleBoard(g, PanelSize, new PointD(0, 0), pcbCount, PanelStep.Name, "0");
            pcbCount++;
            List <IStep.StepAndRepeatClass> srList = PanelStep.GetChildStepClasses();

            foreach (IStep.StepAndRepeatClass sr in srList)
            {
                IStep step = parent.GetStep(sr.NAME);
                System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix();
                matrix.Rotate(-(float)sr.ANGLE, System.Drawing.Drawing2D.MatrixOrder.Append);
                matrix.Translate((float)sr.X, (float)sr.Y, System.Drawing.Drawing2D.MatrixOrder.Append);
                RectangleF BoardSize     = IMath.RectangleTransformWithMatrix(step.GetBoundsD(), matrix).ToRectangleF();
                PointD     originOfBoard = new PointD(sr.X, sr.Y);
                IMath.TransformPoint(matrix, originOfBoard);
                DrawSingleBoard(g, BoardSize, originOfBoard, pcbCount, sr.NAME, sr.ANGLE.ToString("N2"));
                if (sr.NX > 1 || sr.NY > 1)
                {
                    for (int iy = 0; iy < sr.NY; iy++)
                    {
                        for (int ix = 0; ix < sr.NX; ix++)
                        {
                            System.Drawing.Drawing2D.Matrix matrixsr = matrix.Clone();
                            double offsetX = sr.DX * ix;
                            double offsetY = sr.DY * iy;
                            matrixsr.Translate((float)offsetX, (float)offsetY, System.Drawing.Drawing2D.MatrixOrder.Append);
                            BoardSize     = IMath.RectangleTransformWithMatrix(step.GetBoundsD(), matrixsr).ToRectangleF();
                            originOfBoard = new PointD(sr.X + offsetX, sr.Y + offsetY);
                            DrawSingleBoard(g, BoardSize, originOfBoard, pcbCount, sr.NAME, sr.ANGLE.ToString("N2"));
                            pcbCount++;
                        }
                    }
                }
                pcbCount++;
            }
        }
Пример #38
0
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            using (Graphics g = e.Graphics)
            {
                try
                {
                    // рисуем изображение без трасформаций 
                    g.DrawImage(new Bitmap(@"Boxs.bmp"), 0, 0, 100, 100);
                }
                catch { }
                // Создаем матрицу
                Matrix X = new Matrix();
                // Установка трансформаций
                X.RotateAt(45,new Point(150,150));
                X.Translate(100, 100);
                g.Transform = X;
                try
                {
                    // рисуем изображение
                    g.DrawImage(new Bitmap(@"Rings.bmp"), 0, 0, 100, 100);
                }
                catch { }

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

            }

        }
Пример #39
0
 public void AddStringToPath(ISvgRenderer renderer, GraphicsPath path, string text, PointF location)
 {
     var textPath = GetPath(renderer, text, null, false);
     if (textPath.PointCount > 0)
     {
         using (var translate = new Matrix())
         {
             translate.Translate(location.X, location.Y);
             textPath.Transform(translate);
             path.AddPath(textPath, false);
         }
     }
 }
Пример #40
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="flip"></param>
        /// <returns></returns>
        public Image CreateImage(AlignmentType flip)
        {
            Image image = Source;
            Bitmap flippedImage = Opetion != null && Opetion.TragetSize != null
                ? new Bitmap(Opetion.TragetSize.Value.Width, Opetion.TragetSize.Value.Height)
                : new Bitmap(image.Width, image.Height);
            using (Graphics g = Graphics.FromImage(flippedImage))
            {
                //Matrix transformation
                Matrix m = null;
                switch (flip)
                {
                    case AlignmentType.Horizontally | AlignmentType.Vertically:
                        {
                            m = new Matrix(-1, 0, 0, -1, 0, 0);
                            m.Translate(flippedImage.Width, flippedImage.Height, MatrixOrder.Append);
                            break;
                        }
                    case AlignmentType.Horizontally:
                        {
                            m = new Matrix(-1, 0, 0, 1, 0, 0);
                            m.Translate(flippedImage.Width, 0, MatrixOrder.Append);
                            break;
                        }
                    case AlignmentType.Vertically:
                        {
                            m = new Matrix(1, 0, 0, -1, 0, 0);
                            m.Translate(0, flippedImage.Height, MatrixOrder.Append);
                            break;
                        }
                    default: throw new ImageException("Not support");
                }

                //Draw
                g.Transform = m;
                if (Opetion != null)
                {
                    var attributes = GetOpacity(Opetion.Opacity);
                    g.DrawImage(image, new Rectangle(0, 0, flippedImage.Width, flippedImage.Height), 0, 0, flippedImage.Width, flippedImage.Height, GraphicsUnit.Pixel, attributes);
                }
                else
                {
                    g.DrawImage(image, 0, 0);
                }

                //clean up
                m.Dispose();
            }

            return flippedImage;
        }
        // ---------------------------------------------------------------------------
        /**
         * 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();
              }
        }
Пример #42
0
        //private static readonly Point ImageIndent = new Point(2, 2);
        public override void Render(MetroRendererInfo renderingInfo)
        {
            MetroTileItem item = (MetroTileItem)renderingInfo.Control;
            if (item.Frames.Count == 0)
            {
                using (HatchBrush brush = new HatchBrush(HatchStyle.ForwardDiagonal, Color.Red))
                    renderingInfo.PaintEventArgs.Graphics.FillRectangle(brush, item.Bounds);
                return;
            }
            
            Matrix currentTransform = null;
            float zoom = 0.95f;
            System.Drawing.Drawing2D.Matrix mx = null;

            if (renderingInfo.ItemPaintArgs.DragInProgress)
            {
                currentTransform = renderingInfo.PaintEventArgs.Graphics.Transform;
                
                mx = new System.Drawing.Drawing2D.Matrix(zoom, 0, 0, zoom, 0, 0);
                float offsetX = (item.WidthInternal * (1.0f / zoom) - item.WidthInternal) / 2;
                float offsetY = (item.HeightInternal * (1.0f / zoom) - item.HeightInternal) / 2;
                mx.Translate(offsetX, offsetY);
                renderingInfo.PaintEventArgs.Graphics.Transform = mx;
            }

            if (item.CurrentFrameOffset != 0 && item.LastFrame != item.CurrentFrame)
            {
                Graphics g = renderingInfo.PaintEventArgs.Graphics;
                if (currentTransform == null)
                    currentTransform = g.Transform;
                g.TranslateTransform(0, -(item.HeightInternal - item.CurrentFrameOffset - InflatePixels * 2), MatrixOrder.Append);
                // Draw last frame first then offset the current frame
                RenderFrame(renderingInfo, item.LastFrame);
                if (mx != null)
                    g.Transform = mx;
                else
                    g.Transform = currentTransform;
                g.TranslateTransform(0, item.CurrentFrameOffset, MatrixOrder.Append);

                RenderFrame(renderingInfo, item.CurrentFrame);
            }
            else
                RenderFrame(renderingInfo, item.CurrentFrame);

            if (currentTransform != null)
            {
                renderingInfo.PaintEventArgs.Graphics.Transform = currentTransform;
                currentTransform.Dispose();
            }
        }
Пример #43
0
        /// <summary>
        /// This routine draws the animated bomb
        /// using two toggling graphics paths
        /// giving the effect of a spinning bomb
        /// </summary>
        /// <param name="g"></param>
        public override void Draw(Graphics g)
        {
            UpdateBounds();
            Matrix m = new Matrix();

            m.Translate(MovingBounds.Left, MovingBounds.Top);
            // g.FillRectangle(Brushes.White , MovingBounds);
            if (_invert)
            {

                bombInTransformed = (GraphicsPath)bombIn.Clone();
                bombInTransformed.Transform(m);
                g.DrawPath(BombPen, bombInTransformed);
                bombInTransformed.Dispose();
            }
            else
            {
                bombOutTransformed = (GraphicsPath)bombOut.Clone();
                bombOutTransformed.Transform(m);
                g.DrawPath(BombPen, bombOutTransformed);
                bombOutTransformed.Dispose();
            }

              /*          Matrix flipMatrix = new Matrix();
            flipMatrix.Scale(-1.0f, 1.0f);

            m.Translate(MovingBounds.Left, MovingBounds.Top);

            if (_invert)
            {
                m.Scale(-1, 1);  // flip around the y axis
            }

            // g.FillRectangle(Brushes.White , MovingBounds);
                bombInTransformed = (GraphicsPath)bombIn.Clone();
                bombInTransformed.Transform(m);

                g.DrawPath(BombPen, bombInTransformed);
                bombInTransformed.Dispose();
            */

            _invert = !_invert;

            //            g.DrawPolygon(Pens.White, new PointF[]{new PointF(Position.X, Position.Y),
            //                                                   new PointF(Position.X + width, Position.Y + seg),
            //                                                   new PointF(Position.X, Position.Y + seg*2),
            //                                                    new PointF(Position.X + 3, Position.Y + seg*3)});

            Position.Y += TheBombInterval;
        }
Пример #44
0
        public void DrawInto(Graphics g, float offsetX, float offsetY)
        {
            SysMatrix orgM = g.Transform;

            SysMatrix newM = GetMatrix().SysMatrix();

            newM.Multiply(orgM, MatrixOrder.Append);
            newM.Translate(-offsetX, -offsetY, MatrixOrder.Append);
            g.Transform = newM;
            stage.Gdi.RenderInto(Definition, 0, g);
            newM.Dispose();

            g.Transform = orgM;
        }
Пример #45
0
        public static void FileImposition(float width, float height,
            Stream exitStream, int numberDocOfPages, bool rotateSeconds, params Stream[] fileStreams)
        {
            Point currentPoint = null;
            var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

            //http://forums.asp.net/t/1692347.aspx/1
            using (var document = new Document(new Rectangle(width, height)))
            {
                var writer = PdfWriter.GetInstance(document, exitStream);
                {
                    document.Open();
                    var content = writer.DirectContent;
                    document.NewPage();
                    var fileCount = 1;
                    foreach (var fileStream in fileStreams)
                    {
                        var reader = new PdfReader(fileStream);
                        var numberOfPages = reader.NumberOfPages;
                        var isSecond = (fileCount % 2 == 0);
                        if (numberOfPages > 0)
                        {
                            var page = writer.GetImportedPage(reader, 1);
                            var pageRect = reader.GetPageSizeWithRotation(1);
                            var matrix = new Matrix();
                            if (currentPoint == null)
                            {
                                currentPoint = new Point(0, pageRect.Height);
                            }
                            matrix.Translate(currentPoint.X, currentPoint.Y);
                            matrix.Rotate(-90);

                            currentPoint.Y += pageRect.Height;

                            content.AddTemplate(page, matrix);
                            content.BeginText();
                            content.SetFontAndSize(baseFont, 100);
                            content.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Data", currentPoint.X, currentPoint.Y,0);
                            content.EndText();
                            currentPoint.Y += 100;

                        }

                        fileCount++;
                    }

                }
            }
        }
        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);
        }
    /// <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);
                    }
    }
    /// <summary>
    /// Draws path on Graphics
    /// </summary>
    private static void DrawPath()
    {
        using (var bitmap = new Bitmap(640, 480, PixelFormat.Format24bppRgb, RgbColor.White))
            using (var graphics = bitmap.GetAdvancedGraphics())
            {
                var path = CreatePath(graphics);

                graphics.DrawPath(new Pen(RgbColor.Red, 2f), path);

                // Translate coordinates and rotate
                var matrix = new System.Drawing.Drawing2D.Matrix();
                matrix.Translate(bitmap.Width / 3, bitmap.Height / 3);
                matrix.Rotate(30);
                graphics.Transform = matrix;

                graphics.DrawPath(new Pen(RgbColor.Green, 2f), path);

                bitmap.Save("../../../../_Output/DrawPath.tif");
            }
    }
Пример #49
0
        public static Bitmap CreateLine(Device d, GraphicsPath path, Pen pen, bool show_joints)
        {
            RectangleF rectF = path.GetBounds();

            System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix();
            m.Translate(-rectF.X, -rectF.Y);
            path.Transform(m);

            AGT_TextureResource gdi = new AGT_TextureResource(rectF.Width, rectF.Height);

            if (gdi != null)
            {
                Graphics g = gdi.GetGraphics();
                if (g != null)
                {
                    g.DrawPath(pen, path);
                    return(gdi.ToBitmap());
                }
            }
            return(null);
        }
Пример #50
0
        public static Bitmap CreateFillPolygon(Device d, GraphicsPath path, Brush brush)
        {
            RectangleF rectF = path.GetBounds();

            System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix();
            m.Translate(-rectF.X, -rectF.Y);
            path.Transform(m);

            AGT_TextureResource gdi = new AGT_TextureResource(rectF.Width, rectF.Height);

            if (gdi != null)
            {
                Graphics g = gdi.GetGraphics();
                if (g != null)
                {
                    g.FillPath(brush, path);
                    return(gdi.ToBitmap());
                }
            }
            return(null);
        }
        /// <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());
        }
Пример #52
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);
            }
        }
Пример #53
0
        public static Bitmap CreatePolygon(Device d, GraphicsPath path, Pen pen)
        {
            RectangleF rectF = path.GetBounds();

            System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix();
            m.Translate(-rectF.X, -rectF.Y);
            path.Transform(m);

            AGT_TextureResource gdi = new AGT_TextureResource(rectF.Width, rectF.Height);

            if (gdi != null)
            {
                Graphics g = gdi.GetGraphics();
                g.SmoothingMode = SmoothingMode.AntiAlias;
                if (g != null)
                {
                    g.DrawPath(pen, path);
                    return(gdi.ToBitmap());
                }
            }
            return(null);
        }
Пример #54
0
    private void DrawNodes(Drawing.Graphics graphics)
    {
        Drawing2D.Matrix matrix = viewMatrix.Clone();
        int totalHeight         = 0;

        foreach (TreeNodeEx treeNode in this.nodes)
        {
            DrawNode(treeNode, graphics, matrix, ref totalHeight);
            matrix.Translate(0.0f, this.HeightIndent + this.Font.Height);
        }

        this.vScrollBar.Visible = (totalHeight > this.Height);

        if (this.vScrollBar.Visible)
        {
            this.vScrollBar.Maximum = totalHeight - this.Height + this.HeightIndent + this.Font.Height;
        }
        else
        {
            this.viewMatrix.Reset();
            this.vScrollBar.Value = 0;
        }
    }
Пример #55
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);
        }
Пример #56
0
        protected override void OnPaint(PaintEventArgs e)
        {
            try
            {
                System.Drawing.Drawing2D.Matrix mx = new System.Drawing.Drawing2D.Matrix(ZoomFactor, 0, 0, ZoomFactor, 0, 0);
                mx.Translate(this.AutoScrollPosition.X * (1.0f / ZoomFactor), this.AutoScrollPosition.Y * (1.0f / ZoomFactor));

                e.Graphics.Transform = mx;
                if (Model.Items != null)
                {
                    Model.Items.ForEach(x =>
                    {
                        x.View.Draw(e.Graphics);
                    });
                    if (SelectedComponent != null)
                    {
                        SelectedComponent.View.Draw(e.Graphics);
                    }
                }
            }
            catch
            {
            }
        }
Пример #57
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));
        }
Пример #58
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);
        }
Пример #59
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);
        }
Пример #60
0
        void panel_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
        {
            GraphicsPath p = new GraphicsPath();

            // draw A
            p.AddString("A", fontFamily, 0, 250, new System.Drawing.Point(0, 0), new StringFormat());
            p.Flatten(new System.Drawing.Drawing2D.Matrix(), flatness);
            e.Graphics.FillPath(System.Drawing.Brushes.DarkGray, p);
            e.Graphics.DrawPath(new System.Drawing.Pen(System.Drawing.Color.Black, 2.0F), p);
            // draw B
            p.AddString("B", fontFamily, 0, 250, new System.Drawing.Point(0, 250), new StringFormat());
            p.Flatten(new System.Drawing.Drawing2D.Matrix(), flatness);
            e.Graphics.FillPath(System.Drawing.Brushes.DarkGray, p);
            e.Graphics.DrawPath(new System.Drawing.Pen(System.Drawing.Color.Black, 2.0F), p);

            // create polygonA
            p = new GraphicsPath();
            p.AddString("A", fontFamily, 0, 250, new System.Drawing.Point(0, 0), new StringFormat());
            p.Flatten(new System.Drawing.Drawing2D.Matrix(), flatness);
            GpcWrapper.Polygon polygonA = new GpcWrapper.Polygon(p);

            // create polygonB
            p = new GraphicsPath();
            p.AddString("B", fontFamily, 0, 250, new System.Drawing.Point(0, 0), new StringFormat());
            p.Flatten(new System.Drawing.Drawing2D.Matrix(), flatness);
            GpcWrapper.Polygon polygonB = new GpcWrapper.Polygon(p);

            // Save and Load
            polygonA.Save("A.plg", true);
            GpcWrapper.Polygon loadedPolygon = GpcWrapper.Polygon.FromFile("A.plg", true);
            polygonB.Save("B.plg", true);
            GpcWrapper.Polygon loadedPolygon2 = GpcWrapper.Polygon.FromFile("B.plg", true);

            // create Tristrip
            GpcWrapper.Tristrip tristrip  = loadedPolygon.ToTristrip();
            GpcWrapper.Tristrip tristrip2 = loadedPolygon2.ToTristrip();
            for (int i = 0; i < tristrip.NofStrips; i++)
            {
                GpcWrapper.VertexList           vertexList = tristrip.Strip[i];
                GraphicsPath                    path       = vertexList.TristripToGraphicsPath();
                System.Drawing.Drawing2D.Matrix m          = new System.Drawing.Drawing2D.Matrix();
                m.Translate(600, 0);
                path.Transform(m);
                e.Graphics.FillPath(System.Drawing.Brushes.DarkGray, path);
                e.Graphics.DrawPath(Pens.Black, path);
            }
            for (int i = 0; i < tristrip2.NofStrips; i++)
            {
                GpcWrapper.VertexList           vertexList = tristrip2.Strip[i];
                GraphicsPath                    path       = vertexList.TristripToGraphicsPath();
                System.Drawing.Drawing2D.Matrix m          = new System.Drawing.Drawing2D.Matrix();
                m.Translate(600, 250);
                path.Transform(m);
                e.Graphics.FillPath(System.Drawing.Brushes.DarkGray, path);
                e.Graphics.DrawPath(Pens.Black, path);
            }
            PointF[] upperLeftCorner = new PointF[] { new PointF(200, 0), new PointF(200, 250), new PointF(400, 0), new PointF(400, 250) };

            int position = 0;
            int iName    = 0;

            foreach (GpcWrapper.GpcOperation operation in Enum.GetValues(typeof(GpcWrapper.GpcOperation)))
            {
                iName++;
                GpcWrapper.Polygon polygon = polygonA.Clip(operation, polygonB);
                polygon.Save(iName.ToString() + ".plg", true);
                GraphicsPath path = polygon.ToGraphicsPath();
                System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix();
                m.Translate(upperLeftCorner[position].X, upperLeftCorner[position].Y);
                path.Transform(m);
                e.Graphics.FillPath(System.Drawing.Brushes.DarkGray, path);
                e.Graphics.DrawPath(Pens.Black, path);
                position++;
            }
        }