RotateAt() public method

public RotateAt ( float angle, PointF point ) : void
angle float
point PointF
return void
Example #1
0
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            Graphics myGraphics = e.Graphics;
            Pen myPen = new Pen(Color.Black, 1.0f);
            GraphicsPath gp = new GraphicsPath();
            Matrix RotationTransform;

            float centerX = this.Size.Width / 2f;
            float centerY = this.Size.Height / 2f;

            gp.AddPolygon(new PointF[] {
                new PointF(centerX, centerY - 5),
                new PointF(centerX-5, centerY + 5),
                new PointF(centerX+5, centerY + 5)
            });

            RotationTransform = new Matrix(1, 0, 0, 1, 0, 0); // rotation matrix
            PointF RotationPoint = new PointF(centerX, centerY); // rotation point
            RotationTransform.RotateAt(heading, RotationPoint);
            gp.Transform(RotationTransform);

            myGraphics.FillPath(myPen.Brush, gp);
            myGraphics.DrawPath(myPen, gp);
            myPen.Dispose();
            gp.Dispose();
        }
    /// <summary>
    /// Simple rotated text watermark
    /// </summary>
    private static void DrawRotatedTextWatermark()
    {
        using (var bitmap = new Bitmap("../../../../_Input/Venice.jpg"))
            using (var gr = bitmap.GetAdvancedGraphics())
                using (var textPath = new Path())
                {
                    var watermarkColor = new RgbColor(255, 255, 255, 45);

                    var fontSize = UnitConverter.ConvertPixelsToUnits(bitmap.DpiY, bitmap.Height, Unit.Point) / 100.0f;

                    var plainText = new PlainText("Graphics Mill", gr.CreateFont("Arial", fontSize));

                    textPath.DrawText(plainText);

                    var rect = new RectangleF(0, 0, bitmap.Width, bitmap.Height);

                    var transform = new Matrix();
                    transform.RotateAt(-35, new PointF(rect.Left + rect.Width / 2, rect.Top + rect.Height / 2));

                    float offset = plainText.GetBlackBox().Width / 2;

                    using (var tiledTextPath = TilePathText(textPath, GetInvertedRect(rect, transform), offset))
                    {
                        tiledTextPath.ApplyTransform(transform);
                        gr.FillPath(new SolidBrush(watermarkColor), tiledTextPath);
                    }

                    bitmap.Save("../../../../_Output/VeniceRotatedWatermark.jpg");
                }
    }
Example #3
0
		public void Draw(Graphics aGfx, int lX, int lY,bool abBorder,bool abHighLight, int alRotation)
		{
			Matrix Mtx = new Matrix();
			
			float fX = (float)lX;
			float fY = (float)lY;
			
			//Stupid bad fix.
			if(alRotation==1)fY+=0.95f;
			if(alRotation==3)fX+=0.95f;
			PointF vRotPoint = new PointF((float)(lX+mTileImage.Width/2),(float)(lY+mTileImage.Height/2));
			
			Mtx.RotateAt(alRotation*90,vRotPoint, MatrixOrder.Append);
			aGfx.Transform = Mtx;
			
			aGfx.DrawImage(mTileImage,fX,fY,mTileImage.Width,mTileImage.Height);
			
			Mtx.Reset();
			aGfx.Transform = Mtx;
						
			if(abBorder)
			{
				Pen BorderPen; 
				if(abHighLight)BorderPen= new Pen(Color.FromArgb(100,255,100));
				else  BorderPen= new Pen(Color.FromArgb(255,0,255));
				
				if(abHighLight)
					aGfx.DrawRectangle(BorderPen,lX,lY,mTileImage.Width-1, mTileImage.Height-1);
				else
					aGfx.DrawRectangle(BorderPen,lX,lY,mTileImage.Width, mTileImage.Height);

				BorderPen.Dispose();
			}
		}
 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;
 }
Example #5
0
        public static Map InitializeMap(float angle)
        {
            string wmsUrl = "http://dev:8080/geoserver/ows?service=wms&version=1.1.1&request=GetCapabilities";

            Map map = new Map();

            WmsLayer layWms = new WmsLayer("Demis Map", wmsUrl);

            layWms.AddLayer("sf:roads");
            //layWms.AddLayer("Topography");
            //layWms.AddLayer("Hillshading");

            layWms.SetImageFormat(layWms.OutputFormats[0]);
            layWms.ContinueOnError = true;
                //Skip rendering the WMS Map if the server couldn't be requested (if set to false such an event would crash the app)
            layWms.TimeOut = 5000; //Set timeout to 5 seconds
            layWms.SRID = 4326;
            map.Layers.Add(layWms);

            //limit the zoom to 360 degrees width
            map.MaximumZoom = 360;
            map.BackColor = Color.LightBlue;

            map.Zoom = 360;
            map.Center = new Point(0, 0);

            Matrix mat = new Matrix();
            mat.RotateAt(angle, map.WorldToImage(map.Center));
            map.MapTransform = mat;

            map.ZoomToExtents();
            return map;
        }
Example #6
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;
                }
            }
        }
Example #7
0
		/// <summary>
		/// Функция вычисления вершин квадрата по двум смежным вершинам
		/// </summary>
		/// <param name="pt1">Первая вершина</param>
		/// <param name="pt2">Вторая вершина</param>
		/// <returns>Функция возвращает массив точек, являющихся вершинами квадрата</returns>
		PointF[] GetSquareVertices(PointF pt1, PointF pt2) {
			using (System.Drawing.Drawing2D.GraphicsPath square = new System.Drawing.Drawing2D.GraphicsPath()) {
				//Разность координат (с учётом знака)
				float deltaX = pt1.X - pt2.X, deltaY = pt1.Y - pt2.Y;
				//Расстояние между точками
				float dist = (float)Math.Sqrt(Math.Pow(deltaX, 2) + Math.Pow(deltaY, 2));
				//Угол наклона стороны
				double angle;
				//Прямоугольник с вычисленной длиной стороны
				square.AddRectangle(RectangleF.FromLTRB(0, 0, dist, dist));
				//Вычисление угла поворота
				angle = Math.Atan(deltaY / deltaX);
				//Посколько функция Math.Atan возвращает угол в пределах [-π/2;π/2],
				//то нужно пересчитать его в пределы [0;2π]. Для этого смотрим знак разности координат.
				//Квадранты считаются с правого нижнего против часовой стрелки.
				//Первый квадрант [0;π/2) получается сам собой при вычислении арктангенса
				if ((deltaX > 0 && deltaY <= 0) || (deltaX >= 0 && deltaY > 0)) {//Второй квадрант [π/2;π) или третий квадрант [π;3π/2)
					angle = Math.PI + angle;
				}
				else if (deltaX <= 0 && deltaY > 0) {//Четвёртый квадрант [3π/2;2π)
					angle = 2 * Math.PI + angle;
				}
				//Перевод угла из радиан в градусы
				angle *= 180 / Math.PI;
				//Перенос начала координат в первую точку и
				//поворот прямоугольника на вычисленный угол относительно этого нового начала координат
				using (System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix(1, 0, 0, 1, pt.X, pt.Y)) {
					m.RotateAt((float)angle, new PointF());
					square.Transform(m);
				}
				return square.PathPoints;
			}
		}
Example #8
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 #9
0
        private static Map InitializeDXF(float angle)
        {
            Map map = new Map();
            //Set the datasource to a shapefile in the App_data folder
            Ogr provider;
            try
            {
                provider = new Ogr("GeoData/SampleDXF.dxf",0);
            }
            catch (TypeInitializationException ex)
            {
                if (ex.Message == "The type initializer for 'OSGeo.OGR.Ogr' threw an exception.")
                {
                    throw new Exception(
                        String.Format(
                            "The application threw a PINVOKE exception. You probably need to copy the unmanaged dll's to your bin directory. They are a part of fwtools {0}. You can download it from: http://home.gdal.org/fwtools/",
                            GdalRasterLayer.FWToolsVersion));
                }
                throw;
            }
            VectorLayer lay = new VectorLayer("SampleDXF", provider);
            map.Layers.Add(lay);
            map.ZoomToExtents();
            Matrix mat = new Matrix();
            mat.RotateAt(angle, map.WorldToImage(map.Center));
            map.MapTransform = mat;

            _ogrSampleDataset = "SampleDXF";
            return map;

        }
Example #10
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);
        }
Example #11
0
        public static Image mRotateImage(Image inputImg, double degreeAngle)
        {
            //ъглите на image
            PointF[] rotationPoints = { new PointF(0, 0),
                                        new PointF(inputImg.Width, 0),
                                        new PointF(0, inputImg.Height),
                                        new PointF(inputImg.Width, inputImg.Height)};

            //роатция на ъглите
            PointMath.RotatePoints(rotationPoints, new PointF(inputImg.Width / 2.0f, inputImg.Height / 2.0f), degreeAngle);

            //Получаваме новите стойности след ротацията на ъглите

            Rectangle bounds = PointMath.GetBounds(rotationPoints);

            //Празен bitmap за получения завъртян образ
            Bitmap rotatedBitmap = new Bitmap(bounds.Width, bounds.Height);

            using (Graphics g = Graphics.FromImage(rotatedBitmap))
            {
                //Transformation matrix
                Matrix m = new Matrix();
                m.RotateAt((float)degreeAngle, new PointF(inputImg.Width / 2.0f, inputImg.Height / 2.0f));

                g.Transform = m;
                g.DrawImage(inputImg, 0, 0);
            }
            return (Image)rotatedBitmap;
        }
Example #12
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;
		}
 public virtual void Rotate(float angle, PointF center)
 {
     Matrix tempMatrix = new Matrix();
     tempMatrix.RotateAt(angle, center);
     tempMatrix.Multiply(TransformationMatrix);
     TransformationMatrix = tempMatrix;
 }
Example #14
0
        public static byte[] Generate()
        {
            string captchaString = random.Next(1000, 9999).ToString();
            HttpContext.Current.Session["captcha"] = captchaString;

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

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

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

            return ms.GetBuffer();
        }
Example #15
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));
        }
Example #16
0
    //</snippet3>

    // The following code example demonstrates using a Matrix
    // and the GraphicsPath.Transform method to rotate a string.
    // This example is designed to be used with Windows Forms.
    // Create a form and paste the following code into it. Call the
    // DrawVerticalStringFromBottomUp method in the form's Paint
    // event-handling method, passing e as PaintEventArgs.
    //<snippet5>
    public void DrawVerticalStringFromBottomUp(PaintEventArgs e)
    {
        // Create the string to draw on the form.
        string text = "Can you read this?";

        // Create a GraphicsPath.
        System.Drawing.Drawing2D.GraphicsPath path =
            new System.Drawing.Drawing2D.GraphicsPath();

        // Add the string to the path; declare the font, font style, size, and
        // vertical format for the string.
        path.AddString(text, this.Font.FontFamily, 1, 15,
                       new PointF(0.0F, 0.0F),
                       new StringFormat(StringFormatFlags.DirectionVertical));

        // Declare a matrix that will be used to rotate the text.
        System.Drawing.Drawing2D.Matrix rotateMatrix =
            new System.Drawing.Drawing2D.Matrix();

        // Set the rotation angle and starting point for the text.
        rotateMatrix.RotateAt(180.0F, new PointF(10.0F, 100.0F));

        // Transform the text with the matrix.
        path.Transform(rotateMatrix);

        // Set the SmoothingMode to high quality for best readability.
        e.Graphics.SmoothingMode =
            System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        // Fill in the path to draw the string.
        e.Graphics.FillPath(Brushes.Red, path);

        // Dispose of the path.
        path.Dispose();
    }
        /// <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);
            }
        }
    protected override void ApplyTextWatermark(ImageProcessingActionExecuteArgs args, Graphics g)
    {
        // Draw a filled rectangle
        int rectangleWidth = 14;

        using (Brush brush = new SolidBrush(Color.FromArgb(220, Color.Red)))
        {
            g.FillRectangle(brush, new Rectangle(args.Image.Size.Width - rectangleWidth, 0, rectangleWidth, args.Image.Size.Height));
        }

        using (System.Drawing.Drawing2D.Matrix transform = g.Transform)
        {
            using (StringFormat stringFormat = new StringFormat())
            {
                // Vertical text (bottom -> top)
                stringFormat.FormatFlags = StringFormatFlags.DirectionVertical;
                transform.RotateAt(180F, new PointF(args.Image.Size.Width / 2, args.Image.Size.Height / 2));
                g.Transform = transform;

                // Align: top left, +2px displacement
                // (because of the matrix transformation we have to use inverted values)
                base.ContentAlignment    = ContentAlignment.MiddleLeft;
                base.ContentDisplacement = new Point(-2, -2);

                base.ForeColor = Color.White;
                base.Font.Size = 10;

                // Draw the string by invoking the base Apply method
                base.StringFormat = stringFormat;
                base.ApplyTextWatermark(args, g);
                base.StringFormat = null;
            }
        }
    }
        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 #20
0
 /// <summary>
 /// Rotate figure.
 /// </summary>
 public void Rotate(float angle)
 {
     Clear();
     Matrix matrix = new Matrix();
     matrix.RotateAt(angle, Center);
     graphics.Transform = matrix;
     Draw();
 }
Example #21
0
    public void DrawImage()
    {
        //Creates an output Bitmap
        Bitmap   oOutputBitmap = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb);
        Graphics oGraphics     = Graphics.FromImage(oOutputBitmap);

        oGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;

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

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

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

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

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

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

        MemoryStream oMemoryStream = new MemoryStream();

        oOutputBitmap.Save(oMemoryStream, System.Drawing.Imaging.ImageFormat.Png);
        byte[] oBytes = oMemoryStream.GetBuffer();
        captchaImage = "data:image/png;base64," + Convert.ToBase64String(oBytes, 0, oBytes.Length);
        oOutputBitmap.Dispose();
        oMemoryStream.Close();
    }
Example #22
0
        /// <summary>
        /// Draws the background of the collapsed band
        /// </summary>
        /// <param name="g">The canvas to draw on</param>
        /// <param name="bounds">The bounds of the drawing</param>
        /// <param name="text">The text that should appear into the bar</param>
        /// <param name="font">The font to use when drawing the text</param>
        /// <param name="state">The inputstate of the collapsed band</param>
        public override void DrawNaviBandCollapsedBg(Graphics g, Rectangle bounds, string text, Font font,
                                                     bool rightToLeft, InputState state)
        {
            using (SolidBrush b = new SolidBrush(ColourTable.BandCollapsedBgColor1))
            {
                if (state == InputState.Hovered)
                {
                    b.Color = ColourTable.BandCollapsedHoveredColor1;
                }
                else if (state == InputState.Clicked)
                {
                    b.Color = ColourTable.BandCollapsedClickedColor1;
                }

                g.FillRectangle(b, bounds);
            }

            // inner border
            using (Pen p = new Pen(ColourTable.Border))
            {
                g.DrawLine(p, new Point(bounds.Left, bounds.Top), new Point(bounds.Right,
                                                                            bounds.Top));
                p.Color = ColourTable.BorderInner;
                if (state == InputState.Normal)
                {
                    g.DrawLine(p, new Point(bounds.Left, bounds.Top + 1), new Point(bounds.Right,
                                                                                    bounds.Top + 1));
                    g.DrawLine(p, new Point(bounds.Left, bounds.Top + 1), new Point(bounds.Left,
                                                                                    bounds.Bottom));
                }
            }

            using (Brush brush = new SolidBrush(ColourTable.Text))
            {
                if (rightToLeft)
                {
                    Point ptCenter = new Point(bounds.X + bounds.Width / 2 + 7, bounds.Y +
                                               bounds.Height / 2);
                    System.Drawing.Drawing2D.Matrix transform = g.Transform;
                    transform.RotateAt(90, ptCenter);
                    g.Transform = transform;
                    using (StringFormat format = new StringFormat())
                    {
                        format.FormatFlags |= StringFormatFlags.DirectionRightToLeft;
                        g.DrawString(text, font, brush, ptCenter, format);
                    }
                }
                else
                {
                    Point ptCenter = new Point(bounds.X + bounds.Width / 2 - 7, bounds.Y +
                                               bounds.Height / 2);
                    System.Drawing.Drawing2D.Matrix transform = g.Transform;
                    transform.RotateAt(270, ptCenter);
                    g.Transform = transform;
                    g.DrawString(text, font, brush, ptCenter);
                }
            }
        }
Example #23
0
        protected override void UpdatePath()
        {
            InternalPath = new GraphicsPath();
            InternalPath.AddPie(this.Left, this.Top, this.Width, this.Height, this.StartAngle, this.SweepAngle);

            Matrix mtx = new Matrix();
            mtx.RotateAt(this.Rotation, InternalRotationBasePoint);
            InternalPath.Transform(mtx);
        }
Example #24
0
		public void Rotate(float degrees)
		{
			Matrix translateMatrix = new Matrix();
			RectangleF rectF = mPath.GetBounds();
			
			translateMatrix.RotateAt(degrees, new PointF(rectF.Width / 2, rectF.Height /2));
			mPath.Transform(translateMatrix);
			translateMatrix.Dispose();
		}
Example #25
0
 /// <summary>
 /// Draws the picture to the graphics.
 /// </summary>
 /// <param name="g">The g.</param>
 public void Draw(Graphics g)
 {
     Point drawLocation = new Point((int)(location.X - offset.X), (int)(location.Y - offset.Y));
     Matrix m = new Matrix();
     m.RotateAt(-angle, location);
     g.Transform = m;
     g.DrawImage(bitmap, new Rectangle(drawLocation.X, drawLocation.Y, bitmap.Width / this.frameCountW, bitmap.Height / this.frameCountH),
         new Rectangle(this.frameW * bitmap.Width / this.frameCountW, this.frameH * bitmap.Height / this.frameCountH, bitmap.Width / this.frameCountW, bitmap.Height / this.frameCountH), GraphicsUnit.Pixel);
 }
Example #26
0
        protected override void UpdatePath()
        {
            InternalPath = new GraphicsPath();
            InternalPath.AddArc(_left, _top, _width, _height, _startAngle, _sweepAngle);

            Matrix mtx = new Matrix();
            mtx.RotateAt(this.Rotation, InternalRotationBasePoint);
            InternalPath.Transform(mtx);
        }
Example #27
0
        // Return a bitmap rotated around its center.
        public static Bitmap RotateBitmap(Bitmap bm, float angle)
        {
            // Make a Matrix to represent rotation
            // by this angle.
            System.Drawing.Drawing2D.Matrix rotate_at_origin = new System.Drawing.Drawing2D.Matrix();
            rotate_at_origin.Rotate(angle);

            // Rotate the image's corners to see how big
            // it will be after rotation.
            PointF[] points =
            {
                new PointF(0,                0),
                new PointF(bm.Width,         0),
                new PointF(bm.Width, bm.Height),
                new PointF(0,        bm.Height),
            };
            rotate_at_origin.TransformPoints(points);
            float xmin, xmax, ymin, ymax;

            GetPointBounds(points, out xmin, out xmax,
                           out ymin, out ymax);

            // Make a bitmap to hold the rotated result.
            int    wid    = (int)Math.Round(xmax - xmin);
            int    hgt    = (int)Math.Round(ymax - ymin);
            Bitmap result = new Bitmap(wid, hgt);

            // Create the real rotation transformation.
            Matrix rotate_at_center = new Matrix();

            rotate_at_center.RotateAt(angle,
                                      new PointF(wid / 2f, hgt / 2f));

            // Draw the image onto the new bitmap rotated.
            using (Graphics gr = Graphics.FromImage(result))
            {
                // Use smooth image interpolation.
                gr.InterpolationMode = InterpolationMode.High;

                // Clear with the color in the image's upper left corner.
                gr.Clear(bm.GetPixel(0, 0));

                //// For debugging. (It's easier to see the background.)
                //gr.Clear(Color.LightBlue);

                // Set up the transformation to rotate.
                gr.Transform = rotate_at_center;

                // Draw the image centered on the bitmap.
                int x = (wid - bm.Width) / 2;
                int y = (hgt - bm.Height) / 2;
                gr.DrawImage(bm, x, y);
            }

            // Return the result bitmap.
            return(result);
        }
Example #28
0
        public static Map InitializeMapOrig(float angle)
        {
            //Initialize a new map of size 'imagesize'
            Map map = new Map();

            //Set up the countries layer
            VectorLayer layRoads = new VectorLayer("Roads");
            //Set the datasource to a shapefile in the App_data folder
            layRoads.DataSource = new ShapeFile("GeoData/World/shp_textonpath/DeMo_Quan5.shp", false);
            (layRoads.DataSource as ShapeFile).Encoding = Encoding.UTF8;
            //Set fill-style to green
            layRoads.Style.Fill = new SolidBrush(Color.Yellow);
            layRoads.Style.Line = new Pen(Color.Yellow, 4);
            //Set the polygons to have a black outline
            layRoads.Style.Outline = new Pen(Color.Black, 5); ;
            layRoads.Style.EnableOutline = true;
            layRoads.SRID = 4326;

            //Set up a country label layer
            LabelLayer layLabel = new LabelLayer("Roads labels");
            layLabel.DataSource = layRoads.DataSource;
            layLabel.Enabled = true;
            layLabel.LabelColumn = "tenduong";
            layLabel.LabelFilter = SharpMap.Rendering.LabelCollisionDetection.ThoroughCollisionDetection;
            layLabel.Style = new LabelStyle();
            layLabel.Style.ForeColor = Color.White;
            layLabel.Style.Font = new Font(FontFamily.GenericSerif, 9f, FontStyle.Bold);
            layLabel.Style.Halo = new Pen(Color.Black, 2f);
            layLabel.Style.IsTextOnPath = true;
            layLabel.Style.CollisionDetection = true;
            //layLabel.Style.BackColor = new SolidBrush(Color.FromArgb(128, 255, 0, 0));
            //layLabel.MaxVisible = 90;
            //layLabel.MinVisible = 30;
            layLabel.Style.HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Center;
            layLabel.SRID = 4326;
            //layLabel.MultipartGeometryBehaviour = LabelLayer.MultipartGeometryBehaviourEnum.Largest;

          
            //Add the layers to the map object.
            //The order we add them in are the order they are drawn, so we add the rivers last to put them on top
            map.Layers.Add(layRoads);          
            map.Layers.Add(layLabel);        


            //limit the zoom to 360 degrees width
            //map.MaximumZoom = 360;
           // map.BackColor = Color.LightBlue;

            map.ZoomToExtents();

            Matrix mat = new Matrix();
            mat.RotateAt(angle, map.WorldToImage(map.Center));
            map.MapTransform = mat;

            return map;
        }
        public override void Draw(Graphics g, convertToDestinationDelegate convertToDestination, double pixelScale)
        {
            Point startPoint = convertToDestination(StartPoint);
            Point endPoint   = convertToDestination(EndPoint);

            double lenght = (int)Math.Sqrt(Math.Pow(endPoint.X - startPoint.X, 2) + Math.Pow(endPoint.Y - startPoint.Y, 2));

            string text = string.Format("{0} mm", Math.Round(lenght / pixelScale, 0));

            int width = 2;

            Pen pen = new Pen(this.Color, width);

            pen.Alignment = PenAlignment.Inset;
            pen.StartCap  = LineCap.DiamondAnchor;
            pen.EndCap    = LineCap.DiamondAnchor;

            g.DrawLine(pen, startPoint, endPoint);

            path = new GraphicsPath();
            path.StartFigure();
            path.AddLine(startPoint.X, startPoint.Y - width, startPoint.X + (int)lenght, startPoint.Y - width);
            path.AddLine(startPoint.X + (int)lenght, startPoint.Y - width, startPoint.X + (int)lenght, startPoint.Y + width);
            path.AddLine(startPoint.X + (int)lenght, startPoint.Y + width, startPoint.X, startPoint.Y + width);


            float cos = (float)(endPoint.X - startPoint.X) / (float)lenght;


            float arc = (float)(Math.Acos(cos) * (float)180 / Math.PI);

            if (endPoint.Y - startPoint.Y < 0)
            {
                arc = 360 - arc;
            }
            System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix();
            matrix.RotateAt(arc, startPoint);
            path.Transform(matrix);
            path.CloseFigure();


            GraphicsPath pathString = new GraphicsPath();

            pathString.StartFigure();
            pathString.AddString(text,
                                 new FontFamily("Arial"), (int)FontStyle.Regular
                                 ,
                                 16,
                                 new PointF(startPoint.X + (int)lenght / 2 - 20, startPoint.Y - 30),
                                 StringFormat.GenericDefault);

            pathString.Transform(matrix);
            pathString.CloseFigure();

            g.FillPath(new SolidBrush(this.Color), pathString);
        }
Example #30
0
 public static void DrawRectangleRotated(Graphics g, Rectangle r, float angle, Pen pen)
 {
     using (Matrix m = new Matrix())
     {
         m.RotateAt(angle, new PointF(r.Left + (r.Width / 2), r.Top + (r.Height / 2)));
         g.Transform = m;
         g.DrawRectangle(pen, r);
         g.ResetTransform();
     }
 }
Example #31
0
 private void DrawArrow(Graphics g, Point source, Point target)
 {
     Matrix rotateMatrix = new Matrix();
     rotateMatrix.RotateAt((float)GetDegree(target, source), target);
     g.Transform = rotateMatrix;
     g.FillPolygon(EdgeBrush, new Point[] { target,
             new Point(target.X + ArrowSize, target.Y + ArrowSize / 2),
             new Point(target.X + ArrowSize, target.Y - ArrowSize / 2) });
     g.Transform = new Matrix();
 }
Example #32
0
 //***************************************************************************
 // Static Methods
 //
 public static TriangleF Rotate(TriangleF tri, float degrees, PointF center)
 {
     PointF[] p = new PointF[] { new PointF(tri.PointA.X, tri.PointA.Y), new PointF(tri.PointB.X, tri.PointB.Y), new PointF(tri.PointC.X, tri.PointC.Y) };
     using (System.Drawing.Drawing2D.Matrix mat = new System.Drawing.Drawing2D.Matrix())
     {
         mat.RotateAt(degrees, center);
         mat.TransformPoints(p);
     }
     return(new TriangleF(p[0], p[1], p[2]));
 }
        public Bitmap RotateBitmap(Bitmap bm, float angle)
        {
            // Make a Matrix to represent rotation
            // by this angle.
            Matrix rotate_at_origin = new Matrix();
            rotate_at_origin.Rotate(angle);

            // Rotate the image's corners to see how big
            // it will be after rotation.
            PointF[] points =
            {
                new PointF(0, 0),
                new PointF(bm.Width, 0),
                new PointF(bm.Width, bm.Height),
                new PointF(0, bm.Height),
                 };

            rotate_at_origin.TransformPoints(points);
            float xmin, xmax, ymin, ymax;
            GetPointBounds(points, out xmin, out xmax,
                out ymin, out ymax);

            // Make a bitmap to hold the rotated result.
            int wid = (int)Math.Round(xmax - xmin);
            int hgt = (int)Math.Round(ymax - ymin);
            Bitmap result = new Bitmap(wid, hgt);

            // Create the real rotation transformation.
            Matrix rotate_at_center = new Matrix();
            rotate_at_center.RotateAt(angle,
                new PointF(0, 0));

            // Draw the image onto the new bitmap rotated.
            using (Graphics gr = Graphics.FromImage(result))
            {
                // Use smooth image interpolation.
                gr.InterpolationMode = InterpolationMode.HighQualityBilinear;

                // Clear with the color in the image's upper left corner.
                gr.Clear(bm.GetPixel(0, 0));

                gr.Clear(Color.White);

                // Set up the transformation to rotate.
                gr.Transform = rotate_at_center;

                // Draw the image centered on the bitmap.
                int x = 0;
                int y = 0;
                gr.DrawImage(bm, x, y);
            }
            // Return the result bitmap.
            return result;
        }
Example #34
0
		protected override void UpdatePath()
		{
            if (this.Points == null || this.Points.Length == 0) return;

			InternalPath = new GraphicsPath();
			InternalPath.AddCurve(this.Points);

			Matrix mtx = new Matrix();
			mtx.RotateAt(this.Rotation, InternalRotationBasePoint);
			InternalPath.Transform(mtx);
		}
Example #35
0
        public PointF PointToScreenSpace(PointF pntIn)
        {
            System.Drawing.Drawing2D.Matrix mat = new System.Drawing.Drawing2D.Matrix();

            PointF[] tempPoints = new PointF[1];
            tempPoints[0] = new PointF(pntIn.X, pntIn.Y);

            mat.RotateAt(selectionSet[0].RotationAngle, new PointF((float)(selectionSet[0].X), (float)(selectionSet[0].Y)));
            mat.TransformPoints(tempPoints);
            return(tempPoints[0]);
        }
Example #36
0
 public void Draw(Graphics gr)
 {
     gr.Clear(Color.White);
     Matrix matrix = new Matrix();
     for (int i = 0; i < FigureCount; i++)
     {
         gr.DrawImage(image, 0, 0);
         matrix.RotateAt(RotateAngle, new PointF(startPoint.X + image.Width/2, startPoint.Y));
         gr.Transform = matrix;
     }
 }
        public static void RotateRect(Graphics g, Rectangle r, float angle, Color color)
        {
            using (Matrix m = new Matrix())
            {
                m.RotateAt(angle, new PointF(r.Left + (r.Width / 2), r.Top + (r.Height / 2)));
                g.Transform = m;
                SolidBrush br = new SolidBrush(color);
                g.FillRectangle(br, r);

                g.ResetTransform();
            }
        }
Example #38
0
        public virtual void Draw(Graphics g, Tank t)
        {
            // TODO: Fill here

            Rectangle rect = new Rectangle((int)pos.X - width / 2, (int)pos.Y - height / 2, width, height);

            Matrix m = new Matrix();
            m.RotateAt((float)orientation, pos);

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

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

            }

        }
Example #40
0
        public void ChangeDirection(Point pt, Size sz)
        {
            float angle = 90;
            Matrix matrix = new Matrix();
            matrix.RotateAt(angle, pt);

            int n = pointList.Count;
            Point[] points = new Point[n];
            pointList.CopyTo(points);
            matrix.TransformPoints(points);

            for (int i = 0; i < n; i++)
            {
                Rectangle rc = new Rectangle(0, 0, sz.Width, sz.Height);
                if (!rc.Contains(points[i]))
                {
                    if (points[n - 2].X == points[n - 1].X)
                    {
                        int height = Math.Abs(points[1].Y - points[0].Y);
                        if (points[i].Y < 0)
                        {
                            points[0].Y = 1;
                            points[1].Y = points[0].Y + height;
                        }
                        else if (points[i].Y > sz.Height)
                        {
                            points[0].Y = sz.Height - 2;
                            points[1].Y = points[0].Y - height;
                        }
                    }
                    else if (points[n - 2].Y == points[n - 1].Y)
                    {
                        int width = Math.Abs(points[1].X - points[0].X);
                        if (points[i].X < 0)
                        {
                            points[0].X = 1;
                            points[1].X = points[0].X + width;
                        }
                        else if (points[i].X > sz.Width)
                        {
                            points[0].X = sz.Width - 2;
                            points[1].X = points[0].X - width;
                        }
                    }
                    pointList.Clear();
                    pointList.AddRange(points);
                    return;
                }
            }
            pointList.Clear();
            pointList.AddRange(points);
        }
Example #41
0
        public static PointF[] RectToPolygon(RectangleF r, double orientation)
        {
            PointF center = new PointF(r.X + r.Width / 2.0F, r.Y + r.Height / 2.0F);
            PointF TL     = new PointF(r.Left, r.Top);
            PointF TR     = new PointF(r.Right, r.Top);
            PointF BL     = new PointF(r.Left, r.Bottom);
            PointF BR     = new PointF(r.Right, r.Bottom);

            PointF[] points = new PointF[] { BL, TL, TR, BR, BL };
            System.Drawing.Drawing2D.Matrix m = new System.Drawing.Drawing2D.Matrix();
            m.RotateAt((float)orientation, center);
            m.TransformPoints(points);
            return(points);
        }
Example #42
0
        public void Draw(KalikoImage image) {
            var graphics = image.Graphics;
            var graphicsPath = new GraphicsPath();
            var stringFormat = new StringFormat {
                Alignment = Alignment,
                LineAlignment = VerticalAlignment
            };

            graphics.SmoothingMode = SmoothingMode.AntiAlias;
            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

            if (Font == null) {
                Font = image.Font ?? new Font("Arial", 32, FontStyle.Bold, GraphicsUnit.Pixel);
            }

            if (TargetArea == Rectangle.Empty) {
                TargetArea = new Rectangle(0, 0, image.Width, image.Height);
            }

            if (Point == Point.Empty) {
                graphicsPath.AddString(Text, Font.FontFamily, (int)Font.Style, Font.Size, TargetArea, stringFormat);
            }
            else {
                graphicsPath.AddString(Text, Font.FontFamily, (int)Font.Style, Font.Size, Point, stringFormat);
            }

            if (Rotation != 0) {
                var rotationTransform = new Matrix(1, 0, 0, 1, 0, 0);
                var bounds = graphicsPath.GetBounds();
                rotationTransform.RotateAt(Rotation, new PointF(bounds.X + (bounds.Width / 2f), bounds.Y + (bounds.Height / 2f)));
                graphicsPath.Transform(rotationTransform);
            }

            if (TextShadow != null) {
                DrawShadow(graphics, graphicsPath);
            }

            if (Outline > 0) {
                var pen = new Pen(OutlineColor, Outline) {
                    LineJoin = LineJoin.Round
                };
                graphics.DrawPath(pen, graphicsPath);
            }

            if (TextBrush == null) {
                TextBrush = new SolidBrush(TextColor);
            }

            graphics.FillPath(TextBrush, graphicsPath);
        }
Example #43
0
        /// <summary>
        /// 绘制根据点旋转文本,一般旋转点给定位文本包围盒中心点
        /// </summary>
        /// <param name="s">文本</param>
        /// <param name="font">字体</param>
        /// <param name="brush">填充</param>
        /// <param name="point">旋转点</param>
        /// <param name="format">布局方式</param>
        /// <param name="angle">角度</param>
        public void DrawString(string s, Font font, Brush brush, PointF point, StringFormat format, float angle)
        {
            // Save the matrix
            System.Drawing.Drawing2D.Matrix mtxSave = _graphics.Transform;

            System.Drawing.Drawing2D.Matrix mtxRotate = _graphics.Transform;
            mtxRotate.RotateAt(angle, point);
            _graphics.Transform = mtxRotate;

            _graphics.DrawString(s, font, brush, point, format);

            // Reset the matrix
            _graphics.Transform = mtxSave;
        }
Example #44
0
        /// <summary>
        /// Draw this shape onto a bitmap.
        /// </summary>
        /// <param name="graphics">Graphics object to draw with.</param>
        /// <param name="cache">Gdi cache.</param>
        public void DrawShape(Graphics graphics, GdiCache cache)
        {
            if (!IsValid)
            {
                return;
            }

            PointF point  = cache.Projection.MapToBitmap(Location);
            PointF anchor = point;

            Font font = cache.ParseFont(Font, out string _);

            if (font == null)
            {
                font = SystemFonts.CaptionFont;
            }

            Brush fill = new SolidBrush(Colour);
            SizeF size = graphics.MeasureString(Text, font);

            point.X -= 0.5f * size.Width;
            point.Y -= 0.5f * size.Height;

            if (!HorizontalAlignment.Equals(0.0))
            {
                float dx = (float)HorizontalAlignment * 0.5f * size.Width;
                point.X += dx;
            }
            if (!VerticalAlignment.Equals(0.0))
            {
                float dy = (float)VerticalAlignment * 0.5f * size.Height;
                point.Y += dy;
            }
            if (Rotation.Equals(0.0))
            {
                graphics.DrawString(Text, font, fill, point);
            }
            else
            {
                System.Drawing.Drawing2D.Matrix matrix = graphics.Transform;
                System.Drawing.Drawing2D.Matrix rot    = matrix.Clone();
                rot.RotateAt((float)Rotation, anchor);
                graphics.Transform = rot;
                graphics.DrawString(Text, font, fill, point);
                graphics.Transform = matrix;
            }

            fill.Dispose();
        }
Example #45
0
        internal static Map InitializeMap(float angle, string[] filenames)
        {
            var providers = new SharpMap.Data.Providers.Ogr[filenames.Length];
            for (int i = 0; i < filenames.Length; i++)
            {
                providers[i] = new Ogr(filenames[i]);
            }

            var map = LayerTools.GetMapForProviders(providers);

            Matrix mat = new Matrix();
            mat.RotateAt(angle, map.WorldToImage(map.Center));
            map.MapTransform = mat;
            map.ZoomToExtents();
            return map;
        }
 public static Bitmap CropRotatedRect(Bitmap source, Rectangle rect, float angle)
 {
     Bitmap result = new Bitmap(rect.Width, rect.Height);
     using (Graphics g = Graphics.FromImage(result))
     {
         g.InterpolationMode = InterpolationMode.HighQualityBicubic;
         using (Matrix mat = new Matrix())
         {
             mat.Translate(-rect.Location.X, -rect.Location.Y);
             mat.RotateAt(angle, rect.Location);
             g.Transform = mat;
             g.DrawImage(source, new System.Drawing.Point(0, 0));
         }
     }
     return result;
 }
        public override void Draw(Graphics g, convertToDestinationDelegate convertToDestination, double PixelScale)
        {
            Point startPoint = convertToDestination(StartPoint);
            Point endPoint   = convertToDestination(EndPoint);

            int lenght = (int)Math.Sqrt(Math.Pow(endPoint.X - startPoint.X, 2) + Math.Pow(endPoint.Y - startPoint.Y, 2));

            Width = 5;

            if (lenght > 50 && lenght < 150)
            {
                Width = lenght / 10;
            }
            else if (lenght > 100)
            {
                Width = 15;
            }

            Pen pen = new Pen(this.Color, Width);

            pen.EndCap = LineCap.ArrowAnchor;

            g.DrawLine(pen, startPoint, endPoint);

            path = new GraphicsPath();
            path.StartFigure();
            path.AddLine(startPoint.X, startPoint.Y - Width, startPoint.X + lenght, startPoint.Y - Width);
            path.AddLine(startPoint.X + lenght, startPoint.Y - Width, startPoint.X + lenght, startPoint.Y + Width);
            path.AddLine(startPoint.X + lenght, startPoint.Y + Width, startPoint.X, startPoint.Y + Width);

            float cos = (float)(endPoint.X - startPoint.X) / (float)lenght;


            float arc = (float)(Math.Acos(cos) * (float)180 / Math.PI);

            if (endPoint.Y - startPoint.Y < 0)
            {
                arc = 360 - arc;
            }
            System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix();
            matrix.RotateAt(arc, startPoint);
            path.Transform(matrix);
            path.CloseFigure();
        }
Example #48
0
        private void CT_UI_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;

            if (!started)
            {
                g.DrawImage(img, new Point(x, y));
            }
            else
            {
                System.Drawing.Drawing2D.Matrix m = g.Transform;
                //here we do not need to translate, we rotate at the specified point
                float x = (float)(23 / 2) + (float)carpanel.Location.X;
                float y = (float)(12 / 2) + (float)carpanel.Location.Y;
                m.RotateAt(carpanel.Angle, new PointF(x, y), System.Drawing.Drawing2D.MatrixOrder.Append);
                g.Transform = m;
                g.DrawImage(CT_Helper.resizeImage(Properties.Resources.Taxi_GTA2, new Size(23, 12)), new Point(carpanel.Location.X - 11, carpanel.Location.Y - 6));
            }
        }
Example #49
0
        private void drawCenteredArc(Graphics g, float offX, float offY, float size, float height, float penWidth, Color color, float rotation, float tension)
        {
            PointF ptStart  = new PointF(screen.Width / 2 + offX - size / 2, screen.Height / 2 + offY);
            PointF ptEnd    = new PointF(screen.Width / 2 + offX + size / 2, screen.Height / 2 + offY);
            PointF ptMiddle = new PointF(screen.Width / 2 + offX, screen.Height / 2 + offY + height / 2);

            Matrix m = new Matrix();

            m.RotateAt(rotation, ptMiddle);
            g.MultiplyTransform(m);

            Pen pen = new Pen(color, penWidth);

            pen.StartCap = LineCap.Round;
            pen.EndCap   = LineCap.Round;
            g.DrawCurve(pen, new PointF[] { ptStart, ptMiddle, ptEnd }, tension);

            g.ResetTransform();

            pen.Dispose();
        }
Example #50
0
        // Function to Fire the Arrow
        private void FireArrow()
        {
            // If the Player is currently Aiming
            if (meTargetPracticeState == ETargetPracticeGameStates.Aiming)
            {
                // Switch to Shooting the Arrow
                meTargetPracticeState = ETargetPracticeGameStates.FiredArrow;

                // Set the Arrows Velocity based on the current Pitch and Amplitude of the Players voice

                // Find the Middle Point of the Bow And Arrow to Rotate around
                PointF sMiddlePoint = new Point();
                sMiddlePoint.X = mrBOW_AND_ARROW_POSITION.X + (mrBOW_AND_ARROW_POSITION.Width / 2.0f);
                sMiddlePoint.Y = mrBOW_AND_ARROW_POSITION.Y + (mrBOW_AND_ARROW_POSITION.Height / 2.0f);

                // Rotate the Bow And Arrow by the specified Bow And Arrow Rotation Amount
                System.Drawing.Drawing2D.Matrix sRotationMatrix = new System.Drawing.Drawing2D.Matrix(1, 0, 0, 1, 0, 0);
                sRotationMatrix.RotateAt(miBowAndArrowRotation, sMiddlePoint);
                PointF[] sPoint = new PointF[1];
                sPoint[0].X = sMiddlePoint.X + 1;
                sPoint[0].Y = sMiddlePoint.Y;
                sRotationMatrix.TransformPoints(sPoint);

                // Set the Arrows initial Direction to travel
                mcArrowVelocity.X = sPoint[0].X - sMiddlePoint.X;
                mcArrowVelocity.Y = sPoint[0].Y - sMiddlePoint.Y;
                mcArrowVelocity.Normalize();

                // Set the Arrows initial speed
                mcArrowVelocity   *= (mfUnitBowAndArrowPower * 300.0f);
                mcArrowVelocity.X += 100.0f;

                // Set the Arrows Rotation to be the same as the Bow And Arrow initially
                miArrowRotation = miBowAndArrowRotation;

                // Play the Fire Arrow sound
                CFMOD.PlaySound(msSoundFire, false);
            }
        }
Example #51
0
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            int W = img.Width;
            int H = img.Height;

            int R = (int)Math.Sqrt(Math.Pow(W / 2, 2) + Math.Pow(H / 2, 2));

            Graphics gr = e.Graphics;

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

            float degrees = (float)(180 * angle / Math.PI);

            Point PtLoc = new Point(0, 0);

            mat.RotateAt(degrees, new PointF(PtLoc.X + W / 2, PtLoc.Y + H / 2));


            e.Graphics.Transform = mat;

            e.Graphics.DrawImage(img, 0, 0, W, H);
        }
Example #52
0
        public void ProcessRequest(HttpContext context)
        {
            int    iHeight = 80;
            int    iWidth  = 190;
            Random oRandom = new Random();

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

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

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

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

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

            oGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;

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

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

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

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

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

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


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

            MemoryStream oMemoryStream = new MemoryStream();

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


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

            context.Response.BinaryWrite(oBytes);
            context.Response.End();
        }
Example #53
0
        /// <summary>
        /// 添加文字水印
        /// </summary>
        /// <param name="originalFile">目标文件</param>
        /// <param name="markText">水印文字</param>
        /// <param name="waterMarkPosition">水印位置</param>
        /// <returns></returns>
        public bool AddWaterMarkText(string originalFile, string markText, WaterMarkPositions waterMarkPosition)
        {
            try
            {
                Image    image     = new Bitmap(originalFile);
                Graphics draw      = Graphics.FromImage(image);
                int      imgWidth  = image.Width;
                int      imgHeight = image.Height;

                Font  crFont = null;
                SizeF crSize = new SizeF();
                if (FontSize != 0)
                {
                    crFont = new Font(MyFontFamily, FontSize, FontStyle.Bold);
                    crSize = draw.MeasureString(markText, crFont);
                }
                else
                {
                    #region 文字最佳适配
                    int[] sizes = new int[] { 32, 30, 28, 26, 24, 20, 18, 16, 14, 12, 10, 8, 6, 4 };
                    for (int i = 0; i < sizes.Length; i++)
                    {
                        crFont = new Font(MyFontFamily, sizes[i], FontStyle.Bold);
                        crSize = draw.MeasureString(markText, crFont);

                        if ((ushort)crSize.Width < (ushort)imgWidth && (ushort)crSize.Height < (ushort)imgHeight)
                        {
                            break;
                        }
                    }
                    #endregion
                }

                float xpos = 0;
                float ypos = 0;

                switch (waterMarkPosition)
                {
                case WaterMarkPositions.TOP_LEFT:
                    xpos = ((float)imgWidth * (float).01) + (crSize.Width / 2);
                    ypos = (float)imgHeight * (float).01;
                    break;

                case WaterMarkPositions.TOP_RIGHT:
                    xpos = ((float)imgWidth * (float).99) - (crSize.Width / 2);
                    ypos = (float)imgHeight * (float).01;
                    break;

                case WaterMarkPositions.BOTTOM_LEFT:
                    xpos = ((float)imgWidth * (float).01) + (crSize.Width / 2);
                    ypos = ((float)imgHeight * (float).99) - crSize.Height;
                    break;

                case WaterMarkPositions.BOTTOM_RIGHT:
                    xpos = ((float)imgWidth * (float).99) - (crSize.Width / 2);
                    ypos = ((float)imgHeight * (float).99) - crSize.Height;
                    break;

                case WaterMarkPositions.CENTER:
                    xpos = ((float)imgWidth * (float).50);
                    ypos = ((float)imgHeight * (float).50) - crSize.Height;
                    break;
                }

                StringFormat StrFormat = new StringFormat();
                StrFormat.Alignment = StringAlignment.Center;

                SolidBrush semiTransBrush  = new SolidBrush(Color.FromArgb(153, 255, 255, 255));
                SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(153, 0, 0, 0));

                //尝试旋转
                System.Drawing.Drawing2D.Matrix myMatrix = new System.Drawing.Drawing2D.Matrix();
                myMatrix.RotateAt(Angle, new PointF(xpos, ypos), System.Drawing.Drawing2D.MatrixOrder.Append);
                draw.Transform = myMatrix;

                //写出文字
                draw.DrawString(markText, crFont, semiTransBrush, xpos, ypos, StrFormat);
                //加写一层阴影效果
                draw.DrawString(markText, crFont, semiTransBrush2, xpos + 1, ypos + 1, StrFormat);

                semiTransBrush2.Dispose();
                semiTransBrush.Dispose();
                Image imageOut = new Bitmap(image, imgWidth, imgHeight);
                image.Dispose();
                draw.Dispose();
                //删除原始文件
                //if (File.Exists(OriginalFile))
                //{
                //  File.Delete(OriginalFile);
                //}
                //保存新文件
                imageOut.Save(originalFile, ImageFormat.Jpeg);
                imageOut.Dispose();

                if (receiveMessage != null)
                {
                    receiveMessage(string.Format("添加文字水印成功:“{0}”", originalFile));
                }

                return(true);
            }
            catch (Exception ex)
            {
                if (receiveMessage != null)
                {
                    receiveMessage(string.Format("添加文字水印失败:“{0}”,错误:{1}", originalFile, ex));
                }
                return(false);
            }
        }
Example #54
0
        public void Form1_Paint(object sender, PaintEventArgs e)
        {
            //////    // Create a graphics path and add an ellipse.
            //////    GraphicsPath myPath = new GraphicsPath();
            //////    Rectangle rect = new Rectangle(100, 20, 100, 50);
            //////    myPath.AddRectangle(rect);
            //////    // Get the path's array of points.
            //////    PointF[] myPathPointArray = myPath.PathPoints;
            //////    // Create a path gradient brush.
            //////    PathGradientBrush myPGBrush = new
            //////    PathGradientBrush(myPathPointArray);
            //////    // Set the color span.
            //////    myPGBrush.CenterColor = Color.Green;
            //////    Color[] mySurroundColor = { Color.Blue };
            //////    myPGBrush.SurroundColors = mySurroundColor;
            //////    // Draw the brush to the screen prior to transformation.
            //////    e.Graphics.FillRectangle(myPGBrush, 10, 10, 200, 200);
            //////    // Apply the rotate transform to the brush.
            //////    myPGBrush.RotateTransform(a, MatrixOrder.Append);
            //////    // Draw the brush to the screen again after applying the
            //////    // transform.
            //////    e.Graphics.FillRectangle(myPGBrush, 10, 10, 200, 300);
            GraphicsPath path = new GraphicsPath(); int Wi = 0; int Hi = 0;

            path.AddEllipse(160, 70, 150, 70);

            // Use the path to construct a brush.
            PathGradientBrush pthGrBrush = new PathGradientBrush(path);

            // Set the color at the center of the path to blue.
            pthGrBrush.CenterColor = Color.FromArgb(255, 0, 0, 255);
            //pthGrBrush.FocusScales = new PointF(40, 40);
            // Set the color along the entire boundary
            // of the path to aqua.
            Color[] colors = { Color.FromArgb(255, 0, 255, 255) };
            pthGrBrush.SurroundColors = colors;


            pthGrBrush.RotateTransform(a);

            for (int t = 0; t < 100; t++)
            {
                PointF wq = new PointF(); wq.X = 40; wq.Y = 40; pthGrBrush.TranslateTransform(1, 1); e.Graphics.FillRectangle(pthGrBrush, 0, 0, 700, 700); Invalidate();
            }


            Bitmap bm = new Bitmap(img.Width, img.Height);

            if (a <= 90)
            {
                Wi = (int)(bm.Width * Math.Cos(2 * Math.PI * a / 360) + bm.Height * Math.Sin(2 * Math.PI * a / 360));
                Hi = (int)(bm.Height * Math.Cos(2 * Math.PI * a / 360) + bm.Width * Math.Sin(2 * Math.PI * a / 360));
            }
            else if (a > 90 && a <= 180)
            {
                Wi = (int)(bm.Width * -Math.Cos(2 * Math.PI * a / 360) + bm.Height * Math.Sin(2 * Math.PI * a / 360));
                Hi = (int)(bm.Height * -Math.Cos(2 * Math.PI * a / 360) + bm.Width * Math.Sin(2 * Math.PI * a / 360));
            }
            else if (a > 180 && a <= 270)
            {
                Wi = (int)(bm.Width * -Math.Cos(2 * Math.PI * a / 360) + bm.Height * -Math.Sin(2 * Math.PI * a / 360));
                Hi = (int)(bm.Height * -Math.Cos(2 * Math.PI * a / 360) + bm.Width * -Math.Sin(2 * Math.PI * a / 360));
            }
            else if (a > 270 && a <= 360)
            {
                Wi = (int)(bm.Width * Math.Cos(2 * Math.PI * a / 360) + bm.Height * -Math.Sin(2 * Math.PI * a / 360));
                Hi = (int)(bm.Height * Math.Cos(2 * Math.PI * a / 360) + bm.Width * -Math.Sin(2 * Math.PI * a / 360));
            }
            Bitmap b = new Bitmap(Wi, Hi);



            g.TranslateTransform(Wi / 2, Hi / 2);
            g.RotateTransform(a);
            g.TranslateTransform(-img.Width / 2, -img.Height / 2);

            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.DrawImage(img, 0, 0);
            e.Graphics.TranslateTransform(this.Width / 2, this.Height / 2);
            e.Graphics.DrawImage(b, -b.Width / 2, -b.Height / 2);

            Create the string to draw on the form.
            string text = "Roma prodakshen";

            // Create a GraphicsPath.
            System.Drawing.Drawing2D.GraphicsPath path =
                new System.Drawing.Drawing2D.GraphicsPath();

            // Add the string to the path; declare the font, font style, size, and
            // vertical format for the string.
            path.AddString(text, this.Font.FontFamily, 1, 15,
                           new PointF(100.0F, 50.0F),
                           new StringFormat(StringFormatFlags.DirectionVertical));

            // Declare a matrix that will be used to rotate the text.
            System.Drawing.Drawing2D.Matrix rotateMatrix =
                new System.Drawing.Drawing2D.Matrix();

            // Set the rotation angle and starting point for the text.
            rotateMatrix.RotateAt(a, new PointF(200.0F, 50.0F));

            // Transform the text with the matrix.
            path.Transform(rotateMatrix);

            // Set the SmoothingMode to high quality for best readability.
            e.Graphics.SmoothingMode =
                System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            // Fill in the path to draw the string.
            e.Graphics.FillPath(Brushes.GreenYellow, path);

            // Dispose of the path.
            path.Dispose();
        }
Example #55
0
        /// <summary>
        /// 添加图片水印
        /// </summary>
        /// <param name="originalFile">目标文件</param>
        /// <param name="markImgFile">水印图片文件</param>
        /// <param name="waterMarkPosition">水印位置</param>
        /// <param name="degrees">旋转角度,以底边为准</param>
        /// <returns></returns>
        public bool AddWaterMarkImg(string originalFile, string markImgFile, WaterMarkPositions waterMarkPosition, int offset, int degrees)
        {
            try
            {
                //转化为弧度
                double dblDegrees = degrees * Math.PI / 180;

                Image    image   = new Bitmap(originalFile);
                Image    imgMark = new Bitmap(markImgFile);
                Graphics g       = Graphics.FromImage(image);
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                int ImgWidth  = image.Width;
                int ImgHeight = image.Height;

                int ImgMarkWidth  = imgMark.Width;
                int ImgMarkHeight = imgMark.Height;

                //计算旋转后水印图片实际所占的宽高,并为了不超过原图片大小计算其自动缩放比例,再求出四角的坐标
                //底边所占宽高
                double dblHeight = 0.0;
                double dblWidth  = 0.0;
                dblHeight += ImgMarkWidth * Math.Sin(dblDegrees);
                dblHeight += ImgMarkHeight * Math.Sin(90 - dblDegrees);
                dblWidth  += ImgMarkHeight * Math.Sin(dblDegrees);
                dblWidth  += ImgMarkWidth * Math.Sin(90 - dblDegrees);
                //缩放,未加入正弦运算
                double dblScaleVal = 1.0; //私有缩放比例
                if (dblWidth > ImgWidth || dblHeight > ImgHeight)
                {
                    dblScaleVal = (dblWidth / ImgWidth > dblHeight / ImgHeight) ? dblHeight / ImgHeight : dblWidth / ImgWidth;
                }
                int newW = Convert.ToInt16(dblScaleVal * ImgMarkWidth);
                int newH = Convert.ToInt16(dblScaleVal * ImgMarkHeight);
                imgMark = new Bitmap(imgMark, newW, newH);

                #region 自己计算,有点问题
                ////四角坐标
                //Point plt = new Point(), prt = new Point(), plb = new Point(); //左上、右上、左下
                //switch (waterMarkPosition)
                //{
                //  case WaterMarkPositions.TOP_LEFT:
                //    plt = new Point(Offset, Convert.ToInt32(Offset + newW * Math.Sin(Degrees)));
                //    prt = new Point(Convert.ToInt32(newW * Math.Sin(90 - Degrees) + Offset), Convert.ToInt32(Offset));
                //    plb = new Point(Convert.ToInt32(newH * Math.Sin(Degrees) + Offset),
                //      Convert.ToInt32(Offset + newW * Math.Sin(Degrees) + newH * Math.Sin(90 - Degrees)));
                //    break;
                //  case WaterMarkPositions.TOP_RIGHT:
                //    plt = new Point(Convert.ToInt32(ImgWidth - newW * Math.Sin(90 - Degrees) - Offset), Offset);
                //    prt = new Point(Convert.ToInt32(ImgWidth - Offset), Convert.ToInt32(Offset + newW * Math.Sin(Degrees)));
                //    plb = new Point(Convert.ToInt32(ImgWidth - Offset - newH * Math.Sin(Degrees) - newW * Math.Sin(90 - Degrees)),
                //      Convert.ToInt32(Offset + newH * Math.Sin(90 - Degrees)));
                //    break;
                //  case WaterMarkPositions.BOTTOM_LEFT:
                //    plt = new Point(Convert.ToInt32(Offset + newH * Math.Sin(Degrees)),
                //      Convert.ToInt32(ImgHeight - Offset - newH * Math.Sin(90 - Degrees) - newW * Math.Sin(Degrees)));
                //    prt = new Point(Convert.ToInt32(Offset + newW * Math.Sin(90 - Degrees) + newH * Math.Sin(Degrees)),
                //      Convert.ToInt32(ImgHeight - Offset - newH * Math.Sin(90 - Degrees)));
                //    plb = new Point(Offset, Convert.ToInt32(ImgHeight - Offset - newW * Math.Sin(90 - Degrees)));
                //    break;
                //  case WaterMarkPositions.BOTTOM_RIGHT:
                //    plt = new Point(Convert.ToInt32(ImgWidth - Offset - newH * Math.Sin(Degrees) - newW * Math.Sin(90 - Degrees)),
                //      Convert.ToInt32(ImgHeight - Offset - newH * Math.Sin(90 - Degrees)));
                //    prt = new Point(Convert.ToInt32(ImgWidth - Offset - newH * Math.Sin(Degrees)),
                //      Convert.ToInt32(ImgHeight - Offset - newW * Math.Sin(Degrees) - newH * Math.Sin(90 - Degrees)));
                //    plb = new Point(Convert.ToInt32(ImgWidth - Offset - newW * Math.Sin(90 - Degrees)),
                //      Convert.ToInt32(ImgHeight - Offset));
                //    break;
                //  case WaterMarkPositions.CENTER:
                //    break;
                //}
                //Point[] destPara = { plt, prt, plb };
                //draw.DrawImage(imgMark, destPara);
                #endregion

                #region 几何变换旋转
                //对角线计算
                double dblDiagonal = Math.Sqrt(Math.Pow(newW, 2) + Math.Pow(newH, 2));
                //旋转中心点,以水印图片为准,并以中心为准计算水印左上角定点起始位置;
                PointF plt = new PointF(), pCenter = new PointF();
                switch (waterMarkPosition)
                {
                case WaterMarkPositions.TOP_LEFT:
                    //pCenter = new PointF(Offset + (newH * (float)Math.Sin(dblDegrees) + newW * (float)Math.Cos(dblDegrees) / 2),
                    //  Offset + (newH * (float)Math.Cos(dblDegrees) + newW * (float)Math.Sin(dblDegrees) / 2));
                    //plt = new PointF(pCenter.X - (float)dblDiagonal / 2 * (float)Math.Sin(Math.PI / 2 - 2 * dblDegrees),
                    //  pCenter.Y - (float)dblDiagonal / 2 * (float)Math.Cos(Math.PI / 2 - 2 * dblDegrees));
                    break;

                case WaterMarkPositions.TOP_RIGHT:
                    break;

                case WaterMarkPositions.BOTTOM_LEFT:
                    break;

                case WaterMarkPositions.BOTTOM_RIGHT:
                    plt = new PointF(ImgWidth - offset - newW, ImgHeight - offset - newH);
                    break;

                case WaterMarkPositions.CENTER:
                    plt = new PointF(ImgWidth / 2 - newW / 2 - offset, ImgHeight / 2 - newH / 2 - offset);
                    break;
                }
                //plt = new PointF(10, 10); pCenter = new PointF(162, 82);
                System.Drawing.Drawing2D.Matrix myMatrix = new System.Drawing.Drawing2D.Matrix();
                myMatrix.RotateAt(degrees, pCenter, System.Drawing.Drawing2D.MatrixOrder.Prepend);
                //draw.Transform = myMatrix;
                g.DrawImage(imgMark, plt);
                #endregion

                Image imageCopy = new Bitmap(image);
                image.Dispose();
                imgMark.Dispose();
                g.Dispose();
                //删除原始文件
                if (File.Exists(originalFile))
                {
                    File.Delete(originalFile);
                }
                //保存新文件
                imageCopy.Save(originalFile, ImageFormat.Jpeg);
                imageCopy.Dispose();

                if (receiveMessage != null)
                {
                    receiveMessage(string.Format("添加图片水印成功:“{0}”", originalFile));
                }

                return(true);
            }
            catch (Exception ex)
            {
                if (receiveMessage != null)
                {
                    receiveMessage(string.Format("添加图片水印失败:“{0}”,错误:{1}", originalFile, ex));
                }
                return(false);
            }
        }
        /// <summary>
        /// Draws the background of the collapsed band
        /// </summary>
        /// <param name="g">The canvas to draw on</param>
        /// <param name="bounds">The bounds of the drawing</param>
        /// <param name="text">The text that should appear into the bar</param>
        /// <param name="font">The font to use when drawing the text</param>
        /// <param name="state">The inputstate of the collapsed band</param>
        public override void DrawNaviBandCollapsedBg(Graphics g, Rectangle bounds, string text, Font font,
                                                     bool rightToLeft, InputState state)
        {
            // Gradient background
            Color[] endColors = new Color[] { ColourTable.BandCollapsedBgColor1, ColourTable.BandCollapsedBgColor2 };

            if (state == InputState.Clicked)
            {
                endColors = new Color[] { ColourTable.BandCollapsedClickedColor1, ColourTable.BandCollapsedClickedColor1 }
            }
            ;
            else if (state == InputState.Hovered)
            {
                endColors = new Color[] { ColourTable.BandCollapsedHoveredColor1, ColourTable.BandCollapsedHoveredColor1 }
            }
            ;

            float[] ColorPositions = { 0.0f, 1.0f };
            ExtDrawing.DrawVertGradient(g, bounds, endColors, ColorPositions);

            bounds.Width  -= 1;
            bounds.Height -= 1;

            if ((state == InputState.Hovered))
            {
                bounds.Inflate(new Size(-1, -1));
                using (Pen p = new Pen(ColourTable.Border))
                {
                    g.DrawRectangle(p, bounds);
                }

                bounds.Inflate(new Size(-1, -1));

                // Background gradient
                if (state == InputState.Hovered)
                {
                    endColors = new Color[] { ColourTable.ButtonHoveredColor1, ColourTable.ButtonHoveredColor2,
                                              ColourTable.ButtonHoveredColor3 }
                }
                ;
                else
                {
                    endColors = new Color[] { ColourTable.ButtonActiveColor1, ColourTable.ButtonActiveColor2,
                                              ColourTable.ButtonActiveColor3 }
                };

                float[] ColorPositions2 = { 0.0f, 0.4f, 1.0f };
                ExtDrawing.DrawHorGradient(g, bounds, endColors, ColorPositions2);

                // Draws a nice shiney glow on the bottom of the button
                endColors = new Color[] { Color.FromArgb(1, ColourTable.ButtonActiveColor4) };
                GraphicsPath path = new GraphicsPath();
                path.AddEllipse(0, bounds.Height / 2, bounds.Width, bounds.Height);
                ExtDrawing.DrawRadialGradient(g, path, bounds, Color.FromArgb(150,
                                                                              ColourTable.ButtonActiveColor4), endColors);

                // Inner borders
                if (state == InputState.Hovered)
                {
                    using (Pen p = new Pen(ColourTable.BorderInner))
                    {
                        g.DrawRectangle(p, bounds);
                    }
                }
            }
            else if (state == InputState.Clicked)
            {
                bounds.Inflate(new Size(-1, -1));
                using (Pen p = new Pen(ColourTable.Border))
                {
                    g.DrawRectangle(p, bounds);
                }

                // Background gradient
                endColors = new Color[] { ColourTable.ButtonClickedColor3, ColourTable.ButtonClickedColor2,
                                          ColourTable.ButtonClickedColor1 };

                float[] ColorPositions2 = { 0.0f, 0.8f, 1.0f };
                ExtDrawing.DrawVertGradient(g, bounds, endColors, ColorPositions2);
            }



            using (Brush brush = new SolidBrush(ColourTable.Text))
            {
                if (rightToLeft)
                {
                    Point ptCenter = new Point(bounds.X + bounds.Width / 2 + 7, bounds.Y +
                                               bounds.Height / 2);
                    System.Drawing.Drawing2D.Matrix transform = g.Transform;
                    transform.RotateAt(90, ptCenter);
                    g.Transform = transform;
                    using (StringFormat format = new StringFormat())
                    {
                        format.FormatFlags |= StringFormatFlags.DirectionRightToLeft;
                        g.DrawString(text, font, brush, ptCenter, format);
                    }
                }
                else
                {
                    Point ptCenter = new Point(bounds.X + bounds.Width / 2 - 7, bounds.Y +
                                               bounds.Height / 2);
                    System.Drawing.Drawing2D.Matrix transform = g.Transform;
                    transform.RotateAt(270, ptCenter);
                    g.Transform = transform;
                    g.DrawString(text, font, brush, ptCenter);
                }
            }
        }
Example #57
0
        /// <summary>
        /// Renders extent for triggers and pressureplates
        /// </summary>
        private void DrawTriggerExtent(Graphics g, Map.Object obj, Map.Object underCursor = null)
        {
            ThingDb.Thing tt = ThingDb.Things[obj.Name];
            if (!tt.HasClassFlag(ThingDb.Thing.ClassFlags.TRIGGER))
            {
                return;
            }

            TriggerXfer trigger       = obj.GetExtraData <TriggerXfer>();
            bool        isUnderCursor = false;


            if (underCursor != null)
            {
                isUnderCursor = underCursor.Equals(obj);
            }

            bool isSelected  = mapRenderer.SelectedObjects.Items.Contains(obj);
            bool isSelected2 = MapInterface.RecSelected.Contains(obj);

            if (isSelected && isSelected2 && MapInterface.KeyHelper.ShiftKey)
            {
                isSelected  = false;
                isSelected2 = false;
            }

            if (isSelected || isSelected2)
            {
                if (mapRenderer.proHand && isUnderCursor)
                {
                    MainWindow.Instance.mapView.mapPanel.Cursor = Cursors.Hand;
                }
            }

            int       x           = (int)obj.Location.X;
            int       y           = (int)obj.Location.Y;
            Rectangle triggerRect = new Rectangle(x - trigger.SizeX / 2, y - trigger.SizeY / 2, trigger.SizeX, trigger.SizeY);

            using (var m = new System.Drawing.Drawing2D.Matrix())
            {
                m.RotateAt(45, obj.Location);
                g.Transform = m;

                switch (tt.DrawType)
                {
                case "TriggerDraw":

                    g.DrawRectangle(triggerPen, triggerRect);
                    if (isSelected || isSelected2)
                    {
                        g.FillRectangle(new SolidBrush(Color.FromArgb(100, 0, 255, 0)), triggerRect);
                    }
                    else if (isUnderCursor)
                    {
                        g.FillRectangle(new SolidBrush(Color.FromArgb(60, 0, 255, 0)), triggerRect);
                    }

                    break;

                case "PressurePlateDraw":
                    Rectangle shadeRect = new Rectangle(triggerRect.X + 1, triggerRect.Y + 1, triggerRect.Width, triggerRect.Height);
                    Pen       pen       = new Pen(trigger.BackColor, 1F);
                    g.DrawRectangle(pen, shadeRect);
                    pen = new Pen(trigger.EdgeColor, 1F);
                    g.DrawRectangle(pen, triggerRect);
                    if (isSelected || isSelected2)
                    {
                        g.FillRectangle(new SolidBrush(Color.FromArgb(100, 0, 255, 0)), triggerRect);
                    }
                    else if (isUnderCursor)
                    {
                        g.FillRectangle(new SolidBrush(Color.FromArgb(60, 0, 255, 0)), triggerRect);
                    }
                    break;
                }
                g.ResetTransform();
            }
        }
Example #58
0
        /// <summary>
        /// Draws an object's extent
        /// </summary>
        public void DrawObjectExtent(Graphics g, Map.Object obj, bool draw3D)
        {
            ThingDb.Thing tt     = ThingDb.Things[obj.Name];
            PointF        center = obj.Location;

            if (tt.ExtentType == "CIRCLE")
            {
                PointF t    = new PointF(center.X - tt.ExtentX, center.Y - tt.ExtentX);
                PointF p    = new PointF((center.X) - tt.ExtentX, (center.Y - tt.ZSizeY) - tt.ExtentX);
                Pen    Pen0 = new Pen(Color.Blue, 1);//2
                Pen    rotatePen;

                if ((tt.Class & ThingDb.Thing.ClassFlags.IMMOBILE) != ThingDb.Thing.ClassFlags.IMMOBILE)
                {
                    rotatePen = objMoveablePen;
                }
                else
                {
                    rotatePen = extentPen;
                }

                g.DrawEllipse(rotatePen, new RectangleF(t, new Size(2 * tt.ExtentX, 2 * tt.ExtentX)));

                if (draw3D)
                {
                    //Rectangle r1 = new Rectangle((int)t.X, (int)t.Y - (tt.ZSizeY - tt.ExtentX), tt.ExtentX * 2, tt.ZSizeY + 0);
                    PointF point1 = new PointF(t.X, t.Y);
                    point1.Y += tt.ExtentX;
                    PointF point2 = new PointF(p.X, p.Y);
                    point2.Y += tt.ExtentX;

                    g.DrawLine(rotatePen, point1, point2);

                    point1.X += tt.ExtentX * 2;
                    point2.X += tt.ExtentX * 2;

                    g.DrawLine(rotatePen, point1, point2);


                    g.DrawEllipse(rotatePen, new RectangleF(p, new Size(2 * tt.ExtentX, 2 * tt.ExtentX)));
                    //g.DrawRectangle(Pen0, r1);
                }
            }
            if (tt.ExtentType == "BOX")
            {
                Point t = new Point((int)(center.X - (tt.ExtentX / 2)), (int)(center.Y - (tt.ExtentY / 2)));
                Point p = new Point((int)((center.X - (tt.ZSizeY / 2)) - (tt.ExtentX / 2)), (int)((center.Y - (tt.ZSizeY / 2)) - (tt.ExtentY / 2)));


                using (var m = new System.Drawing.Drawing2D.Matrix())
                {
                    m.RotateAt(45, center);
                    g.Transform = m;
                    Pen rotatePen = new Pen(Color.Green, 1);
                    Pen testPen   = new Pen(Color.Fuchsia, 1);
                    // Pen Pen1 = new Pen(Color.Red, 1);

                    Pen Pen2 = new Pen(Color.Azure, 1);   //0
                    Pen Pen3 = new Pen(Color.Blue, 1);    //2
                    Pen Pen4 = new Pen(Color.Orange, 1);  //1
                    Pen Pen5 = new Pen(Color.Yellow, 1);  //4
                    Pen Pen6 = new Pen(Color.Pink, 1);    //5
                    Pen Pen7 = new Pen(Color.Fuchsia, 1); //3
                    // Pen Pen8 = new Pen(Color.ForestGreen, 1);

                    g.DrawRectangle(rotatePen, new Rectangle(t, new Size(tt.ExtentX, tt.ExtentY)));


                    PointF[] pointss = new PointF[6];
                    if (draw3D)
                    {
                        PointF point1 = new PointF(t.X, t.Y);
                        PointF point2 = new PointF(p.X, p.Y);
                        g.DrawLine(rotatePen, point1, point2);

                        pointss[0] = point2;



                        // g.DrawEllipse(Pen1, new RectangleF(point1, new Size(5, 5)));
                        // g.DrawEllipse(Pen2, new RectangleF(point2, new Size(5, 5)));


                        point1    = new PointF(t.X, t.Y);
                        point2    = new PointF(p.X, p.Y);
                        point1.Y += tt.ExtentY;
                        point2.Y += tt.ExtentY;
                        g.DrawLine(rotatePen, point1, point2);



                        // g.DrawEllipse(Pen3, new RectangleF(point1, new Size(5, 5)));
                        //g.DrawEllipse(Pen4, new RectangleF(point2, new Size(5, 5)));
                        pointss[1] = point2;
                        pointss[2] = point1;


                        point1    = new PointF(t.X, t.Y);
                        point2    = new PointF(p.X, p.Y);
                        point1.X += tt.ExtentX;
                        point2.X += tt.ExtentX;
                        g.DrawLine(rotatePen, point1, point2);

                        // g.DrawEllipse(Pen5, new RectangleF(point1, new Size(5, 5)));
                        // g.DrawEllipse(Pen6, new RectangleF(point2, new Size(5, 5)));
                        pointss[4] = point1;
                        pointss[5] = point2;

                        point1    = new PointF(t.X, t.Y);
                        point2    = new PointF(p.X, p.Y);
                        point1.X += tt.ExtentX;
                        point2.X += tt.ExtentX;

                        point1.Y += tt.ExtentY;
                        point2.Y += tt.ExtentY;


                        //g.DrawEllipse(Pen7, new RectangleF(point1, new Size(5, 5)));
                        //g.DrawEllipse(Pen8, new RectangleF(point2, new Size(5, 5)));
                        pointss[3] = point1;

                        //PointF pivot = GetCentroid(pointss, 6);

                        /*
                         * pointss[0] = Rotate(pointss[0], center, 45);
                         * pointss[1] = Rotate(pointss[1], center, 45);
                         * pointss[2] = Rotate(pointss[2], center, 45);
                         * pointss[3] = Rotate(pointss[3], center, 45);
                         * pointss[4] = Rotate(pointss[4], center, 45);
                         * pointss[5] = Rotate(pointss[5], center, 45);
                         */


                        g.DrawLine(rotatePen, point1, point2);

                        g.DrawRectangle(rotatePen, new Rectangle(p, new Size(tt.ExtentX, tt.ExtentY)));
                        //g.DrawPolygon(testPen, pointss);
                    }
                    g.ResetTransform();
                    // g.DrawPolygon(Pen3, pointss);
                }
            }
        }
Example #59
0
        private Bitmap RotatePic(Bitmap bmpBU, float w, bool keepWholeImg)
        {
            Bitmap   bmp = null;
            Graphics g   = null;

            try
            {
                //Modus
                if (!keepWholeImg)
                {
                    bmp = new Bitmap(bmpBU.Width, bmpBU.Height);

                    g = Graphics.FromImage(bmp);
                    float hw = bmp.Width / 2f;
                    float hh = bmp.Height / 2f;
                    g.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                    //translate center
                    g.TranslateTransform(hw, hh);
                    //rotate
                    g.RotateTransform(w);
                    //re-translate
                    g.TranslateTransform(-hw, -hh);
                    g.DrawImage(bmpBU, 0, 0);
                    g.Dispose();
                }
                else
                {
                    //get the new size and create the blank bitmap
                    float  rad = (float)(w / 180.0 * Math.PI);
                    double fW  = Math.Abs((Math.Cos(rad) * bmpBU.Width)) + Math.Abs((Math.Sin(rad) * bmpBU.Height));
                    double fH  = Math.Abs((Math.Sin(rad) * bmpBU.Width)) + Math.Abs((Math.Cos(rad) * bmpBU.Height));

                    bmp = new Bitmap((int)Math.Ceiling(fW), (int)Math.Ceiling(fH));

                    g = Graphics.FromImage(bmp);

                    g.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                    float hw = bmp.Width / 2f;
                    float hh = bmp.Height / 2f;

                    System.Drawing.Drawing2D.Matrix m = g.Transform;

                    //here we do not need to translate, we rotate at the specified point
                    m.RotateAt(w, new PointF((float)(bmp.Width / 2), (float)(bmp.Height / 2)), System.Drawing.Drawing2D.MatrixOrder.Append);

                    g.Transform = m;

                    //draw the rotated image
                    g.DrawImage(bmpBU, new PointF((float)((bmp.Width - bmpBU.Width) / 2), (float)((bmp.Height - bmpBU.Height) / 2)));
                    g.Dispose();
                }
            }
            catch
            {
                if ((bmp != null))
                {
                    bmp.Dispose();
                    bmp = null;
                }

                if ((g != null))
                {
                    g.Dispose();
                }

                MessageBox.Show("Fehler.");
            }

            return(bmp);
        }
Example #60
0
        public Bitmap Generate(string sCaptchaText)
        {
            int    iHeight = 80;
            int    iWidth  = 190;
            Random oRandom = new Random();

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

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

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

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

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

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

            oGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;

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

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

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

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

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

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

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

                oGraphics.ResetTransform();
            }

            return(oOutputBitmap);
        }