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

public Flatten ( ) : void
Результат void
Пример #1
0
        public Analyzer(double meanX, double meanY, GraphicsPath path)
        {
            Counters = new RunningCount[Enum.GetValues(typeof(AnalysisMetric)).Length];

            foreach(AnalysisMetric metric in Enum.GetValues(typeof(AnalysisMetric)))
                Counters[(int)metric] = new RunningCount(metric);

            MeanX = meanX;
            MeanY = meanY;

            path.Flatten();

            using(GraphicsPathIterator PathIterator = new GraphicsPathIterator(path))
            {
                using(GraphicsPath Subpath = new GraphicsPath())
                {
                    Paths = new List<PointF[]>();

                    bool Closed;

                    while(PathIterator.NextSubpath(Subpath, out Closed) > 0)
                    {
                        Paths.Add(Subpath.PathPoints);
                        Subpath.Reset();
                    }
                }
            }
        }
        public static void WarpPath(GraphicsPath path, PointF[] destPoints, RectangleF srcRect, Matrix matrix = null, WarpMode warpMode = WarpMode.Perspective, float flatness = 0.25f)
        {
            if (path.PointCount == 0)
                return;

            path.Flatten(matrix, flatness);

            var pathData = path.PathData;
            var pnts = path.PathPoints;

            var srcPoints = new PointF[] { new PointF(srcRect.Left, srcRect.Top),
                new PointF(srcRect.Right, srcRect.Top),
                new PointF(srcRect.Left, srcRect.Bottom),
                new PointF(srcRect.Right, srcRect.Bottom) };

            var count = pnts.Length;
            float x1, y1;
            int i;

            if (warpMode == WarpMode.Perspective)
            {
                CalcProjectiveXformCoeffs(srcPoints, destPoints, out coeffs);

                for (i = 0; i < count; i++)
                {
                    x1 = pnts[i].X;
                    y1 = pnts[i].Y;

                    var factor = 1.0f / (coeffs[6] * x1 + coeffs[7] * y1 + 1.0f);
                    pnts[i].X = (float)(factor * (coeffs[0] * x1 + coeffs[1] * y1 + coeffs[2]));
                    pnts[i].Y = (float)(factor * (coeffs[3] * x1 + coeffs[4] * y1 + coeffs[5]));
                }
            }
            else
            {
                CalcBilinearXformCoeffs(srcPoints, destPoints, out coeffs);

                for (i = 0; i < count; i++)
                {
                    x1 = pnts[i].X;
                    y1 = pnts[i].Y;

                    pnts[i].X = (float)(coeffs[0] * x1 + coeffs[1] * y1 + coeffs[2] * x1 * y1 + coeffs[3]);
                    pnts[i].Y = (float)(coeffs[4] * x1 + coeffs[5] * y1 + coeffs[6] * x1 * y1 + coeffs[7]);
                }

            }

            GraphicsPath warpedPath = new GraphicsPath(pnts, pathData.Types);
            if (warpedPath != null)
            {
                FillMode fm = path.FillMode;
                path.Reset();
                path.FillMode = fm;

                path.AddPath(warpedPath, true);
                warpedPath.Dispose();
            }
        }
Пример #3
0
 /// <summary>
 /// Get the desired Rounded Rectangle path.
 /// </summary>
 private static GraphicsPath GetEllipse(RectangleF baseRect)
 {
   GraphicsPath mPath = new GraphicsPath();
   mPath.AddEllipse(baseRect);
   mPath.CloseFigure();
   mPath.Flatten();
   return mPath;
 }
Пример #4
0
        private void Form2_Paint(object sender, PaintEventArgs e)
        {
            //패스 그래디언트
            Point[] pts = { new Point(100, 0), new Point(0, 100), new Point(200, 100) };
            PathGradientBrush B = new PathGradientBrush(pts, WrapMode.Tile);
            e.Graphics.FillRectangle(B, ClientRectangle);

            //패스 그래디언트 끝
            //패스변형
            GraphicsPath Path = new GraphicsPath();
            Path.AddString("한글", new FontFamily("궁서"), 0, 100, new Point(10, 30), new StringFormat());
            //확장 후 외곽선 그리기
            Path.Widen(new Pen(Color.Black, 3));
            e.Graphics.DrawPath(Pens.Black, Path);

            //확장 후 채우기
            Path.Widen(new Pen(Color.Blue, 3));
            e.Graphics.DrawPath(Pens.Black, Path);

            //곡선 펴기
            Path.Flatten(new Matrix(), 12f);
            e.Graphics.DrawPath(Pens.Black, Path);

            //회전
            Matrix M = new Matrix();
            M.Rotate(-10);
            Path.Transform(M);
            e.Graphics.FillPath(Brushes.Blue, Path);

            //휘기
            RectangleF R = Path.GetBounds();
            PointF[] arPoint = new PointF[4];
            arPoint[0] = new PointF(R.Left, R.Top + 30);
            arPoint[1] = new PointF(R.Right, R.Top - 10);
            arPoint[2] = new PointF(R.Left + 10, R.Bottom - 10);
            arPoint[3] = new PointF(R.Right + 30, R.Bottom + 30);

            Path.Warp(arPoint, R);
            e.Graphics.FillPath(Brushes.Blue, Path);

            //클리핑

            //graphicspath path= new graphicspath();
            //path.fillmode = fillmode.winding;
            //path.addellipse(50, 10, 100, 80);
            //path.addellipse(20, 45, 160, 120);
            //e.graphics.fillpath(brushes.white, path);

            //e.graphics.setclip(path);

            //for (int y = 0; y < bottom; y+= 20)
            //{
            //    string str = "눈사람의 모양의클리핑 영역에 글자를 쓴것입니다";
            //    e.graphics.drawstring(str, font, brushes.blue, 0, y);
            //}

            //클리핑 끝
        }
Пример #5
0
        private static void DrawColorWheel(Graphics gr, Color outline_color, int xmin, int ymin, int wid, int hgt)
        {
            Rectangle rect = new Rectangle(xmin, ymin, wid, hgt);
            GraphicsPath wheel_path = new GraphicsPath();
            wheel_path.AddEllipse(rect);
            wheel_path.Flatten();

            float num_pts = (wheel_path.PointCount - 1) / 6;
            Color[] surround_colors = new Color[wheel_path.PointCount];

            int index = 0;
            InterpolateColors(surround_colors, ref index,
                1 * num_pts, 255, 255, 0, 0, 255, 255, 0, 255);
            InterpolateColors(surround_colors, ref index,
                2 * num_pts, 255, 255, 0, 255, 255, 0, 0, 255);
            InterpolateColors(surround_colors, ref index,
                3 * num_pts, 255, 0, 0, 255, 255, 0, 255, 255);
            InterpolateColors(surround_colors, ref index,
                4 * num_pts, 255, 0, 255, 255, 255, 0, 255, 0);
            InterpolateColors(surround_colors, ref index,
                5 * num_pts, 255, 0, 255, 0, 255, 255, 255, 0);
            InterpolateColors(surround_colors, ref index,
                wheel_path.PointCount, 255, 255, 255, 0, 255, 255, 0, 0);

            using (PathGradientBrush path_brush =
                new PathGradientBrush(wheel_path))
            {
                path_brush.CenterColor = Color.White;
                path_brush.SurroundColors = surround_colors;

                gr.FillPath(path_brush, wheel_path);

                // It looks better if we outline the wheel.
                using (Pen thick_pen = new Pen(outline_color, 2))
                {
                    gr.DrawPath(thick_pen, wheel_path);
                }
            }
        }
Пример #6
0
		public void Flatten_Polygon ()
		{
			GraphicsPath path = new GraphicsPath ();
			path.AddPolygon (new Point[4] { 
				new Point (0, 0), new Point (10, 10),
				new Point (20, 20), new Point (40, 40)
				});
			GraphicsPath clone = (GraphicsPath) path.Clone ();
			path.Flatten ();
			ComparePaths (path, clone);
		}
Пример #7
0
		public void Flatten_Pie ()
		{
			GraphicsPath path = new GraphicsPath ();
			path.AddPie (0, 0, 100, 100, 30, 30);
			GraphicsPath clone = (GraphicsPath) path.Clone ();
			path.Flatten ();
			CompareFlats (path, clone);
		}
Пример #8
0
        public void DrawTextOnPath()
        {
            PointF[] tmpPoints;
            PointF[] points = new PointF[25001];
            int count = 0;
            GraphicsPath gp = new GraphicsPath(_pathdata.Points, _pathdata.Types) { FillMode = FillMode.Winding };
            _regionList.Clear();
            gp.Flatten(null, 1);
            try
            {
                PointF tmpPoint = gp.PathPoints[0];
                int i;
                for (i = 0; i <= gp.PathPoints.Length - 2; i++)
                {
                    if (gp.PathTypes[i + 1] == (byte)PathPointType.Start | (gp.PathTypes[i] & (byte)PathPointType.CloseSubpath) == (byte)PathPointType.CloseSubpath)
                    {
                        tmpPoints = GetLinePoints(gp.PathPoints[i], tmpPoint, 1);
                        Array.ConstrainedCopy(tmpPoints, 0, points, count, tmpPoints.Length);
                        count += 1;
                        tmpPoint = gp.PathPoints[i + 1];
                    }
                    else
                    {
                        tmpPoints = GetLinePoints(gp.PathPoints[i], gp.PathPoints[i + 1], 1);
                        Array.ConstrainedCopy(tmpPoints, 0, points, count, tmpPoints.Length);
                        count += tmpPoints.Length - 1;

                    }
                }
                tmpPoints = new PointF[count];
                Array.Copy(points, tmpPoints, count);
                points = CleanPoints(tmpPoints);

                count = points.Length - 1;
                DrawText(points, count);
            }
            catch (Exception ex)
            {
                LastError = ex;

            }
        }
Пример #9
0
        //---------------------------------------------------------------------
        private void GenerateAustPlusRandomEllipses(int count)
        {
            subjects.Clear();
            //load map of Australia from resource ...
            _assembly = Assembly.GetExecutingAssembly();
            polyStream = _assembly.GetManifestResourceStream("GuiDemo.aust.bin");
            int len = (int)polyStream.Length;
            byte[] b = new byte[len];
            polyStream.Read(b, 0, len);
            int polyCnt = BitConverter.ToInt32(b, 0);
            int k = 4;
            for (int i = 0; i < polyCnt; ++i)
            {
                int vertCnt = BitConverter.ToInt32(b, k);
                k += 4;
                Polygon pg = new Polygon(vertCnt);
                for (int j = 0; j < vertCnt; ++j)
                {
                    float x = BitConverter.ToSingle(b, k) * scale;
                    float y = BitConverter.ToSingle(b, k + 4) * scale;
                    k += 8;
                    pg.Add(new IntPoint((int)x, (int)y));
                }
                subjects.Add(pg);
            }

            clips.Clear();
            Random rand = new Random();
            GraphicsPath path = new GraphicsPath();
            Point pt = new Point();

            const int ellipse_size = 100, margin = 10;
            for (int i = 0; i < count; ++i)
            {
                int w = pictureBox1.ClientRectangle.Width - ellipse_size - margin *2;
                int h = pictureBox1.ClientRectangle.Height - ellipse_size - margin * 2 - statusStrip1.Height;

                pt.X = rand.Next(w) + margin;
                pt.Y = rand.Next(h) + margin;
                int size = rand.Next(ellipse_size - 20) + 20;
                path.Reset();
                path.AddEllipse(pt.X, pt.Y, size, size);
                path.Flatten();
                Polygon clip = new Polygon(path.PathPoints.Count());
                foreach (PointF p in path.PathPoints)
                    clip.Add(new IntPoint((int)(p.X * scale), (int)(p.Y * scale)));
                clips.Add(clip);
            }
        }
Пример #10
0
		/// <summary>
		/// Produces DXF output for Flowchart shape
		/// </summary>
		/// <param name="rect">Bounding Rectangle</param>
		/// <param name="ShapeStyle">Flowchart shape style</param>
		/// <param name="st">ElementTemplate reference if shape is complex null otherwise</param>
		/// <param name="crLine">Line color</param>
		/// <param name="RA">Rotation angle</param>
		/// <param name="dash">DashStyle</param>
		/// <param name="LineWidth">Line width ( not used)</param>
		/// <param name="Offset">Offset if it's necessary</param>
		/// <param name="WCS2UCS">if true conversion for world-coordinate to user-coordinate is required</param>
		/// <param name="gr">GraphicsPath to be assigned</param>
		/// <param name="result">>DXF output string</param>
		/// <returns>true if successfull otherwise false</returns>
		public bool Shape2Str( RectangleF rect, BoxStyle ShapeStyle, ElementTemplate[] st, 
			Color crLine, float RA,  DashStyle dash, Single LineWidth, 
			float Offset, bool WCS2UCS, ref GraphicsPath gr, ref string result )
		{
			
			float X	= 0, Y = 0,	X1 = 0,	Y1 = 0,
				X2 = 0,	Y2 = 0,	X3 = 0,	Y3 = 0;
			bool DisableStringOutput = false;
			PointF[] pts = null;
			bool bOk = false;
			string PathPart = "";
			GraphicsPath gr_temp = new GraphicsPath(FillMode.Winding);

			try
			{
		
				if ( gr == null )
					throw new Exception("Empty Graphics Path reference passed");
						

				DisableStringOutput = ( result == null );
			
				// Detecting box's style
				switch (ShapeStyle)
				{
		
					case BoxStyle.Rectangle:
						gr.AddRectangle(rect);
						break;
					case BoxStyle.Ellipse:
						gr.AddEllipse(rect.X,rect.Y,rect.Width,	rect.Height);
						break;
					case BoxStyle.RoundedRectangle:
						gr = Utilities.getRoundRect(rect.X,	rect.Y,	rect.Width,	rect.Height,10);
						break;
					case BoxStyle.Delay:
						gr.AddRectangle(rect);
						break;
					case BoxStyle.Rhombus:
		
						pts = new PointF[4] {new PointF((rect.Left	+ rect.Right) /	2, rect.Top - Offset),
												new PointF(Math.Max(rect.Right, rect.Left) + Offset, (rect.Top	+ rect.Bottom) / 2),
												new PointF((rect.Left	+ rect.Right) /	2,	Math.Max(rect.Bottom, rect.Top) + Offset),
												new PointF(rect.Left - Offset,(rect.Top	+ rect.Bottom) / 2)};
		
									
						gr.AddPolygon(pts);
									
					
						break;
					case BoxStyle.Shape:  // if shape is complex then processing all its elements
						

						if (st  ==	null)
							throw new Exception("Empty shape reference in the complex shape");

						

						foreach	(ElementTemplate et	in st )
						{
							switch ( et.getClassId())
							{
								case 28: // If shape element is arc
						
									ArcTemplate	at =  et as	ArcTemplate;
									double rx = 0, ry = 0 , cx = 0, cy = 0;
					
									rx = rect.Width * (at.Bounds.Width/200);
									ry = rect.Height * (at.Bounds.Height/200);

									cx = rect.X + rect.Width*(at.Bounds.X/100) + rx;
									cy = rect.Y + rect.Height*(at.Bounds.Y/100) + ry;

									gr.AddArc((float) (cx - rx), (float) ( cy - ry) , (float) rx*2, (float) ry*2, at.StartAngle ,at.SweepAngle);

									float StartAngle =  180 + at.StartAngle + (360 - at.SweepAngle) - RA, EndAngle =  StartAngle + at.SweepAngle;

									if ( rx != ry )
									{
										

										float iAngleC = 0;
										double majorx = 0, majory = 0;
									
										
										if (at.StartAngle<0)
											iAngleC = 360 - Math.Abs(at.StartAngle);
										else
											iAngleC = at.StartAngle;


										majorx = (rx < ry) ? 0 : rx;
										majory = (rx < ry) ? ry : 0; 
										
									
										if (( iAngleC >=0 ) && (iAngleC<90))
										{
										
											majorx*=-1;
											majory*=-1;
										}
										else if (( iAngleC >=90 ) && (iAngleC<180))
										{
										
								
										}
										else if (( iAngleC >=180 ) && (iAngleC<270))
										{
								
										
											majorx*=-1;
											majory*=-1;
											
										}
										else if (( iAngleC >=270 ) && (iAngleC<=360))
										{
								
										}
										
									

										
										StartAngle =  at.StartAngle + RA;
										EndAngle =  StartAngle + at.SweepAngle;
										
										if ((at.SweepAngle>=270) && (at.SweepAngle<360))
										{
											if ( ry > rx )
										{
												StartAngle = at.StartAngle + RA + 90 + ( 360 - at.SweepAngle);
												EndAngle = at.StartAngle + RA + 90;
											}
											
										} 
										else if (at.SweepAngle>=180)
										{
											if (ry>rx)
											{
												StartAngle-=90;
												EndAngle-=90;
											}
										
											
										}
										
										
	
										
										
										PathPart = String.Format(provider, "  0\nELLIPSE\n  100\nAcDbEntity\n{0:HAN}  8\n{5}\n  62\n{6:ACI}\n 100\nAcDbEllipse\n  10\n{0:U}\n  20\n{1:U}\n  11\n{7:U}\n  21\n{8:U}\n  40\n{9:U}\n  41\n{3:U}\n  42\n{4:U}\n",
											cx, m_FlowChart.DocExtents.Height - cy,0, (StartAngle*Math.PI)/180 , (EndAngle*Math.PI)/180, SHAPE_LAYER, crLine, majorx , majory , (rx < ry) ? rx/ry : ry/rx);
									}
									else
									{
										
										PathPart = String.Format(provider, "  0\nARC\n  100\nAcDbEntity\n{0:HAN}  8\n{5}\n  62\n{6:ACI}\n 100\nAcDbCircle\n  10\n{0:U}\n  20\n{1:U}\n  40\n{2:U}\n  100\nAcDbArc\n  50\n{3}\n  51\n{4}\n",
											cx, m_FlowChart.DocExtents.Height - cy,rx, StartAngle , EndAngle, SHAPE_LAYER, crLine);
									}

									break;
								case 29: // If shape element is bezier curve

									BezierTemplate	bt =  et as	BezierTemplate;

									X =	rect.X	+ rect.Width * (bt.Coordinates[0]/100);
									Y =	rect.Y	+  rect.Height*	(bt.Coordinates[1]/100);

									X1 = rect.X	 + rect.Width *	(bt.Coordinates[2]/100);
									Y1 = rect.Y	 +	rect.Height* (bt.Coordinates[3]/100);

									X2 = rect.X	 + rect.Width *	(bt.Coordinates[4]/100);
									Y2 = rect.Y	 + rect.Height*	(bt.Coordinates[5]/100);

									X3 = rect.X	 + rect.Width *	(bt.Coordinates[6]/100);
									Y3 = rect.Y	 + rect.Height*	(bt.Coordinates[7]/100);

									
									gr_temp.Reset();
									gr_temp.AddBezier(X,Y,X1,Y1,X2,Y2,X3,Y3);
									gr.AddBezier(X,Y,X1,Y1,X2,Y2,X3,Y3);
									
									// Applying rotation if it's necessary
									pts = RotatePoints(RA , new PointF(rect.X + rect.Width/2,rect.Y + rect.Height/2), gr_temp);

									gr_temp.Flatten();
									PointF[] pts2 = gr_temp.PathData.Points.Clone() as PointF[];
									
									PathPart = String.Format(provider, "0\nPOLYLINE\n{0:HAN}   100\nAcDbEntity\n8\n{0}\n  62\n{1:ACI}\n  100\nAcDb2dPolyline\n  66\n1\n  70\n4\n  75\n6\n{2}{3}0\nSEQEND\n  100\nAcDbEntity\n{0:HAN}", 
										SHAPE_LAYER,
										crLine, 
										Pt2String(pts,crLine,SHAPE_LAYER,DxLineType.ltVertex, dash, 16),
										Pt2String(pts2,crLine,SHAPE_LAYER,DxLineType.ltVertex, dash, 8));

									break;
								case 30:  // If shape element is line


									LineTemplate lt	= et as	LineTemplate;
					
									X1 = rect.X	+ rect.Width * (lt.Coordinates[0]/100);
									Y1 = rect.Y	+ rect.Height* (lt.Coordinates[1]/100);

									X2 = rect.X	+ rect.Width * (lt.Coordinates[2]/100);
									Y2 = rect.Y	+ rect.Height* (lt.Coordinates[3]/100);
									
									gr_temp.Reset();
									gr_temp.AddLine(X1,Y1,X2,Y2);
									gr.AddLine(X1,Y1,X2,Y2);
									
									// Applying rotation if it's necessary
									pts = RotatePoints(RA , new PointF(rect.X + rect.Width/2,rect.Y + rect.Height/2), gr_temp);
									PathPart = Pt2String(pts, crLine,SHAPE_LAYER,DxLineType.ltSingle,DashStyle.Solid, 1);
									break;
							}

							result+=PathPart;
						}
						break;
					default:
						gr.AddRectangle(rect);
						break;

				}


			
				// Converting shapes coordinates from UCS to WSC
				TranslateCoords(RA , new PointF(rect.X + rect.Width/2,rect.Y + rect.Height/2), WCS2UCS, ref gr);
				
				gr.Flatten();

				// If string output is required producing DXF string
				if (!DisableStringOutput)
				{
					if ( result=="" )
					{
						pts = gr.PathPoints.Clone() as PointF[];
						result = Pt2String(pts, crLine, SHAPE_LAYER, DxLineType.ltClosedSingle, dash, LineWidth);
					}
					
				}
				
				bOk = true;
			}
			catch (	Exception ex)
			{

				Trace.WriteLine(String.Format("{0} error {1}\n","Box2Str",ex.Message));
				bOk = false;
			}

			return bOk;
		}
Пример #11
0
    /// <summary>
    /// Creates a rectangular <see cref="GraphicsPath"/> with rounded edges, optionally with an open title
    /// region specified by the parameters <paramref name="titleInset"/> and <paramref name="titleWidth"/>.
    /// </summary>
    /// <param name="baseRect">The rect which surrounds the created path.</param>
    /// <param name="radiusX">The X radius of the rounded edges.</param>
    /// <param name="radiusY">The Y radius of the rounded edges.</param>
    /// <param name="withTitleRegion">If set to <c>true</c>, a title region will be left out.</param>
    /// <param name="titleInset">Inset of the title region behind the corner. This parameter will only be used if
    /// <paramref name="withTitleRegion"/> is set to <c>true</c>.</param>
    /// <param name="titleWidth">Width of the title region to leave out. This parameter will only be used if
    /// <paramref name="withTitleRegion"/> is set to <c>true</c>.</param>
    public static GraphicsPath CreateRoundedRectWithTitleRegionPath(RectangleF baseRect, float radiusX, float radiusY,
        bool withTitleRegion, float titleInset, float titleWidth)
    {
      GraphicsPath result = new GraphicsPath();
      if (radiusX <= 0.0f && radiusY <= 0.0f || baseRect.Width == 0 || baseRect.Height == 0)
      {
        // if corner radius is less than or equal to zero, return the original rectangle
        if (withTitleRegion)
        { // If we should leave out a title region, we need to do it manually, because we need to start next to the
          // title.

          titleWidth = Math.Min(titleWidth, baseRect.Width - 2 * titleInset);
          // Right from the title to the upper right edge
          result.AddLine(baseRect.Left + 2* titleInset + titleWidth, baseRect.Top,
              baseRect.Right, baseRect.Top);
          // Upper right edge to lower right edge
          result.AddLine(baseRect.Right, baseRect.Top,
              baseRect.Right, baseRect.Bottom);
          // Lower right edge to lower left edge
          result.AddLine(baseRect.Right, baseRect.Bottom,
              baseRect.Left, baseRect.Bottom);
          // Lower left edge to upper left edge
          result.AddLine(baseRect.Left, baseRect.Bottom,
              baseRect.Left, baseRect.Top);
          // Upper left edge to the left side of the title
          result.AddLine(baseRect.Left, baseRect.Top, baseRect.Left + titleInset, baseRect.Top);
        }
        else
          result.AddRectangle(baseRect);
      }
      else
      {
        if (radiusX >= baseRect.Width / 2f)
          radiusX = baseRect.Width/2f;
        if (radiusY >= baseRect.Height / 2f)
          radiusY = baseRect.Height/2f;
        // create the arc for the rectangle sides and declare a graphics path object for the drawing 
        SizeF sizeF = new SizeF(radiusX * 2f, radiusY * 2f);
        RectangleF arc = new RectangleF(baseRect.Location, sizeF);

        if (withTitleRegion)
        {
          titleWidth = Math.Min(titleWidth, baseRect.Width - 2 * (radiusX + titleInset));
          // Right of the title to the upper right edge
          result.AddLine(baseRect.Left + radiusX + titleInset + titleWidth, baseRect.Top,
              baseRect.Right - radiusX, baseRect.Top);
        }

        // Top right arc 
        arc.X = baseRect.Right - radiusX * 2f;
        result.AddArc(arc, 270, 90);

        // Bottom right arc 
        arc.Y = baseRect.Bottom - radiusY * 2f;
        result.AddArc(arc, 0, 90);

        // Bottom left arc
        arc.X = baseRect.Left;
        result.AddArc(arc, 90, 90);

        // Top left arc 
        arc.Y = baseRect.Top;
        result.AddArc(arc, 180, 90);

        if (withTitleRegion)
          // Upper left edge to the left side of the title
          result.AddLine(baseRect.Left + radiusX, baseRect.Top, baseRect.Left + radiusX + titleInset, baseRect.Top);
        else
          result.CloseFigure();
      }
      result.Flatten();
      return result;
    }
Пример #12
0
        /// <summary>
        /// Repaints the form with cool background and stuff
        /// </summary>
        /// <param name="graph">The graphics object to paint to, the element will be drawn to 0, 0</param>
        public override void Paint(Graphics graph)
        {
            //Draws Rectangular Shapes
            if (Shape == ModelShape.Arrow)
            {
                _arrowPath = new GraphicsPath();

                //Draws the basic shape
                Pen arrowPen;
                if (Highlight < 1)
                    arrowPen = new Pen(Color.Cyan, 3F);
                else
                    arrowPen = new Pen(Color.Black, 3F);

                //Draws the curved arrow
                Point[] lineArray = new Point[4];
                lineArray[0] = new Point(_startPoint.X, _startPoint.Y);
                lineArray[1] = new Point(_startPoint.X - ((_startPoint.X - _stopPoint.X) / 3), _startPoint.Y);
                lineArray[2] = new Point(_stopPoint.X - ((_stopPoint.X - _startPoint.X) / 3), _stopPoint.Y);
                lineArray[3] = new Point(_stopPoint.X, _stopPoint.Y);
                graph.DrawBeziers(arrowPen, lineArray);
                _arrowPath.AddBeziers(lineArray);
                _arrowPath.Flatten();

                //Draws the arrow head
                Point[] arrowArray = new Point[3];
                arrowArray[0] = _stopPoint;
                arrowArray[1] = new Point(_stopPoint.X - (5 * Math.Sign(_stopPoint.X - _startPoint.X)), _stopPoint.Y - 2);
                arrowArray[2] = new Point(_stopPoint.X - (5 * Math.Sign(_stopPoint.X - _startPoint.X)), _stopPoint.Y + 2);
                graph.DrawPolygon(arrowPen, arrowArray);

                //Garbage collection
                arrowPen.Dispose();
            }
        }
Пример #13
0
		public void Flatten_Empty ()
		{
			GraphicsPath path = new GraphicsPath ();
			GraphicsPath clone = (GraphicsPath) path.Clone ();
			// this is a no-op as there's nothing in the path
			path.Flatten ();
			ComparePaths (path, clone);
		}
Пример #14
0
    //---------------------------------------------------------------------

    private void GenerateAustPlusRandomEllipses(int count)
    {
      subjects.Clear();
      //load map of Australia from resource ...
      Assembly _assembly = Assembly.GetExecutingAssembly();
      using (BinaryReader polyStream = new BinaryReader(_assembly.GetManifestResourceStream("GuiDemo.aust.bin")))
      {
        int polyCnt = polyStream.ReadInt32();
        for (int i = 0; i < polyCnt; ++i)
        {
          int vertCnt = polyStream.ReadInt32();
          Polygon pg = new Polygon(vertCnt);
          for (int j = 0; j < vertCnt; ++j)
          {
            float x = polyStream.ReadSingle() * scale;
            float y = polyStream.ReadSingle() * scale;
            pg.Add(new IntPoint((int)x, (int)y));
          }
          subjects.Add(pg);
        }
      }
      clips.Clear();
      Random rand = new Random();
      using (GraphicsPath path = new GraphicsPath())
      {
        const int ellipse_size = 100, margin = 10;
        for (int i = 0; i < count; ++i)
        {
          int w = pictureBox1.ClientRectangle.Width - ellipse_size - margin * 2;
          int h = pictureBox1.ClientRectangle.Height - ellipse_size - margin * 2 - statusStrip1.Height;

          int x = rand.Next(w) + margin;
          int y = rand.Next(h) + margin;
          int size = rand.Next(ellipse_size - 20) + 20;
          path.Reset();
          path.AddEllipse(x, y, size, size);
          path.Flatten();
          Polygon clip = new Polygon(path.PathPoints.Count());
          foreach (PointF p in path.PathPoints)
            clip.Add(new IntPoint((int)(p.X * scale), (int)(p.Y * scale)));
          clips.Add(clip);
        }
      }
    }
Пример #15
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;
    }
Пример #16
0
		/// <summary>
		/// Build new polygon from ellipse. The ellipse is
		/// defined by the specified bounding rectangle. The
		/// second parameter specifies how close the
		/// polygon approximates the ellipse.
		/// Factor of 0 specifies simplest polygon, while
		/// factor 100 specifies the most complex polygon.
		/// </summary>
		/// <param name="bounds"></param>
		/// <param name="factor"></param>
		public Polygon(RectangleF bounds, int factor)
		{
			if (factor < 0)
				factor = 0;
			if (factor > 100)
				factor = 100;

			GraphicsPath path = new GraphicsPath();

			path.AddEllipse(bounds);
			path.Flatten(new Matrix(), (float)factor / 100f);
			_points = new PointList(path.PathPoints);

			path.Dispose();

			Complete();
		}
Пример #17
0
        public void buildObjectToLua(StringBuilder sb, float XRatio, float YRatio, CoronaObject objectToBuild)
        {
            float moyenneRatio = (XRatio + YRatio) / 2;

            if (objectToBuild.isEntity == false)
            {
                DisplayObject obj = objectToBuild.DisplayObject;

                string objName = obj.Name.Replace(" ", "");
                string paramsName = "params_" + objName;

                //Create Gradient color if enabled
                string gradient = "nil";

                if (obj.GradientColor.isEnabled == true)
                {
                    string color1 = "{" + obj.GradientColor.color1.R + ","
                        + obj.GradientColor.color1.G + ","
                        + obj.GradientColor.color1.B + "}";

                    string color2 = "{" + obj.GradientColor.color2.R + ","
                        + obj.GradientColor.color2.G + ","
                        + obj.GradientColor.color2.B + "}";

                    string direction = "\"" + obj.GradientColor.direction.ToString() + "\"";
                    gradient = "{" + color1 + "," + color2 + "," + direction + "}";
                }

                sb.AppendLine("\tlocal " + paramsName + " = {}");

                if (objectToBuild.EntityParent != null)
                {
                    sb.AppendLine("\t" + paramsName + ".entityParent = " + this.Name.Replace(" ", "") + "." + objectToBuild.EntityParent.Name);
                }

                if (obj.Type.Equals("IMAGE"))
                {

                    Size finalSize = new Size(Convert.ToInt32(obj.SurfaceRect.Size.Width * XRatio), Convert.ToInt32(obj.SurfaceRect.Size.Height * YRatio));
                    String paramsObj = "\t" + paramsName + ".name = \"" + objName + "\"\n" +
                                              "\t" + paramsName + ".type = \"IMAGE\" \n" +
                                              "\t" + paramsName + ".isHandledByTilesMap = " + obj.CoronaObjectParent.IsHandledByTilesMap.ToString().ToLower() + "\n" +
                                             "\t" + paramsName + ".x = " + ((float)obj.SurfaceRect.X * XRatio).ToString().Replace(",", ".") + "\n" +
                                             "\t" + paramsName + ".y = " + ((float)obj.SurfaceRect.Y * YRatio).ToString().Replace(",", ".") + "\n" +
                                             "\t" + paramsName + ".width = " + finalSize.Width.ToString() + "\n" +
                                             "\t" + paramsName + ".height = " + finalSize.Height.ToString() + "\n" +
                                             "\t" + paramsName + ".blendMode = \"" + obj.blendMode + "\"\n" +
                                              "\t" + paramsName + ".rotation = " + obj.Rotation + "\n" +
                                              "\t" + paramsName + ".alpha = " + obj.Alpha.ToString().Replace(",", ".") + "\n" +
                                            "\t" + paramsName + ".gradient = " + gradient + "\n" +
                                             "\t" + paramsName + ".pathImage = \"" + obj.OriginalAssetName.ToLower() + finalSize.Width + "x" + finalSize.Height + ".png\"\n" +
                                             "\t" + paramsName + ".displayGroupParent = " + this.Name.Replace(" ", "") + ".displayGroup\n\n";

                    sb.Append(paramsObj);
                    sb.AppendLine("\t" + paramsName + ".isDraggable = " + obj.CoronaObjectParent.isDraggable.ToString().ToLower());

                    if (obj.CoronaObjectParent.isDraggable == true)
                    {
                        sb.AppendLine("\t" + paramsName + ".dragDamping = " + obj.CoronaObjectParent.DragDamping.ToString().Replace(",", "."));
                        sb.AppendLine("\t" + paramsName + ".dragMaxForce = " + obj.CoronaObjectParent.DragMaxForce);
                        sb.AppendLine("\t" + paramsName + ".dragFrequency = " + obj.CoronaObjectParent.DragFrequency);
                    }

                    if (obj.CoronaObjectParent.isDraggable == true)
                        sb.AppendLine("\t" + paramsName + ".dragBody = dragBody");

                    String createObj = "\t" + this.Name + "." + objName + " = objectInstance.Object.create(" + paramsName + ")";
                    sb.AppendLine(createObj);

                    if (obj.ImageFillColor.IsEmpty == false)
                    {
                        sb.AppendLine("\t" + this.Name + "." + objName + ".object:setFillColor(" +
                            obj.ImageFillColor.R + "," + obj.ImageFillColor.G + "," + obj.ImageFillColor.B + ")");
                    }
                }

                //Sinon si c'est un SPRITE
                else if (obj.Type.Equals("SPRITE"))
                {
                    string sequenceName = obj.CurrentSequence;
                    if (sequenceName == "DEFAULT" || sequenceName == "") sequenceName = "nil";
                    else
                    {
                        sequenceName = "\"" + sequenceName + "\"";
                    }

                    //Creer les params de l'objet
                    String paramsSprite = "\t" + paramsName + ".name = \"" + objName + "\"\n" +
                                             "\t" + paramsName + ".type = \"SPRITE\" \n" +
                                             "\t" + paramsName + ".isHandledByTilesMap = " + obj.CoronaObjectParent.IsHandledByTilesMap.ToString().ToLower() + "\n" +
                                            "\t" + paramsName + ".x = " + ((float)obj.SurfaceRect.X * XRatio).ToString().Replace(",", ".") + "\n" +
                                             "\t" + paramsName + ".y = " + ((float)obj.SurfaceRect.Y * YRatio).ToString().Replace(",", ".") + "\n" +
                                             "\t" + paramsName + ".spriteSet = " + obj.SpriteSet.Name + "\n" +
                                             "\t" + paramsName + ".rotation = " + obj.Rotation + "\n" +
                                             "\t" + paramsName + ".blendMode = \"" + obj.blendMode + "\"\n" +
                                             "\t" + paramsName + ".sequenceName = " + sequenceName+ "\n" +
                                             "\t" + paramsName + ".firstFrameIndex = " + (obj.CurrentFrame +1) + "\n" +
                                              "\t" + paramsName + ".autoPlay = " + obj.AutoPlay.ToString().ToLower() + "\n" +
                                             "\t" + paramsName + ".alpha = " + obj.Alpha.ToString().Replace(",", ".") + "\n" +
                                            "\t" + paramsName + ".gradient = " + gradient + "\n" +
                                            "\t" + paramsName + ".scale = 1/currentSuffix.value\n" +
                                             "\t" + paramsName + ".displayGroupParent = " + this.Name.Replace(" ", "") + ".displayGroup\n\n";

                    //Ajouter la sprite set de l'objet
                    sb.Append(paramsSprite);

                    sb.AppendLine("\t" + paramsName + ".isDraggable = " + obj.CoronaObjectParent.isDraggable.ToString().ToLower());

                    if (obj.CoronaObjectParent.isDraggable == true)
                    {
                        sb.AppendLine("\t" + paramsName + ".dragBody = dragBody");
                        sb.AppendLine("\t" + paramsName + ".dragDamping = " + obj.CoronaObjectParent.DragDamping.ToString().Replace(",", "."));
                        sb.AppendLine("\t" + paramsName + ".dragMaxForce = " + obj.CoronaObjectParent.DragMaxForce);
                        sb.AppendLine("\t" + paramsName + ".dragFrequency = " + obj.CoronaObjectParent.DragFrequency);
                    }

                    sb.AppendLine("\t" + this.Name + "." + objName + " = objectInstance.Object.create(" + paramsName + ")");
                    //if (obj.SpriteSet.Sequences.Count > 0)
                    //    sb.AppendLine("\t" + this.Name + "." + objName + ".currentSequence = \"" + obj.SpriteSet.Sequences[0].Name + "\"");

                }
                else if (obj.Type.Equals("FIGURE"))
                {
                    //Si c'est un rectangle
                    if (obj.Figure.ShapeType.Equals("RECTANGLE"))
                    {
                        //Recuperer le rectangle
                        Rect rect = obj.Figure as Rect;

                        String paramsObj = "\t" + paramsName + ".name = \"" + objName + "\"\n" +
                                             "\t" + paramsName + ".type = \"RECTANGLE\" \n" +
                                             "\t" + paramsName + ".isHandledByTilesMap = " + obj.CoronaObjectParent.IsHandledByTilesMap.ToString().ToLower() + "\n" +
                                             "\t" + paramsName + ".isRounded = " + rect.isRounded.ToString().ToLower() + "\n" +
                                              "\t" + paramsName + ".x = " + ((float)rect.Position.X * XRatio).ToString().Replace(",", ".") + "\n" +
                                              "\t" + paramsName + ".y = " + ((float)rect.Position.Y * YRatio).ToString().Replace(",", ".") + "\n" +
                                              "\t" + paramsName + ".width = " + ((float)rect.Width * XRatio).ToString().Replace(",", ".") + "\n" +
                                              "\t" + paramsName + ".height = " + ((float)rect.Height * YRatio).ToString().Replace(",", ".") + "\n" +
                                             "\t" + paramsName + ".rotation = " + obj.Rotation + "\n" +
                                             "\t" + paramsName + ".blendMode = \"" + obj.blendMode + "\"\n" +
                                            "\t" + paramsName + ".gradient = " + gradient + "\n" +
                                            "\t" + paramsName + ".alpha = " + obj.Alpha.ToString().Replace(",", ".") + "\n";
                        if (rect.isRounded == true)
                        {
                            paramsObj += "\t" + paramsName + ".cornerRadius = " + rect.cornerRadius + "\n";
                        }

                        if (obj.Figure.Fill == true)
                            paramsObj += "\t" + paramsName + ".backColor = { R = " + rect.FillColor.R + ",G = " + rect.FillColor.G + ", B = " + rect.FillColor.B + "}\n";
                        else
                            paramsObj += "\t" + paramsName + ".backColor = { R = 0, G = 0, B= 0}\n";

                        paramsObj += "\t" + paramsName + ".strokeColor = { R = " + rect.StrokeColor.R + ",G = " + rect.StrokeColor.G + ", B = " + rect.StrokeColor.B + "}\n" +
                                                "\t" + paramsName + ".strokeWidth = " + rect.StrokeSize + "\n" +
                                                "\t" + paramsName + ".displayGroupParent = " + this.Name.Replace(" ", "") + ".displayGroup\n\n";

                        sb.Append(paramsObj);

                        sb.AppendLine("\t" + paramsName + ".isDraggable = " + obj.CoronaObjectParent.isDraggable.ToString().ToLower());
                        if (obj.CoronaObjectParent.isDraggable == true)
                        {
                            sb.AppendLine("\t" + paramsName + ".dragBody = dragBody");
                            sb.AppendLine("\t" + paramsName + ".dragDamping = " + obj.CoronaObjectParent.DragDamping.ToString().Replace(",", "."));
                            sb.AppendLine("\t" + paramsName + ".dragMaxForce = " + obj.CoronaObjectParent.DragMaxForce);
                            sb.AppendLine("\t" + paramsName + ".dragFrequency = " + obj.CoronaObjectParent.DragFrequency);
                        }

                        String createObj = "\t" + this.Name + "." + objName + " = objectInstance.Object.create(" + paramsName + ")";
                        sb.AppendLine(createObj);

                    }
                    else if (obj.Figure.ShapeType.Equals("CIRCLE"))
                    {
                        //Recuperer le cercle
                        Cercle cercle = obj.Figure as Cercle;

                        String paramsObj = "\t" + paramsName + ".name = \"" + objName + "\"\n" +
                                                 "\t" + paramsName + ".type = \"CIRCLE\" \n" +
                                                 "\t" + paramsName + ".isHandledByTilesMap = " + obj.CoronaObjectParent.IsHandledByTilesMap.ToString().ToLower() + "\n" +
                                                 "\t" + paramsName + ".x = " + ((float)cercle.Position.X * XRatio).ToString().Replace(",", ".") + "\n" +
                                                 "\t" + paramsName + ".y = " + ((float)cercle.Position.Y * YRatio).ToString().Replace(",", ".") + "\n" +
                                                 "\t" + paramsName + ".radius = " + ((float)cercle.Rayon * moyenneRatio).ToString().Replace(",", ".") + "\n" +
                                                 "\t" + paramsName + ".rotation = " + obj.Rotation + "\n" +
                                                "\t" + paramsName + ".blendMode = \"" + obj.blendMode + "\"\n" +
                                                "\t" + paramsName + ".alpha = " + obj.Alpha.ToString().Replace(",", ".") + "\n";
                        if (obj.Figure.Fill == true)
                            paramsObj += "\t" + paramsName + ".backColor = { R = " + cercle.FillColor.R + ",G = " + cercle.FillColor.G + ", B = " + cercle.FillColor.B + "}\n";
                        else
                            paramsObj += "\t" + paramsName + ".backColor = { R = 0, G = 0, B= 0}\n";

                        paramsObj += "\t" + paramsName + ".strokeColor = { R = " + cercle.StrokeColor.R + ",G = " + cercle.StrokeColor.G + ", B = " + cercle.StrokeColor.B + "}\n" +
                                       "\t" + paramsName + ".strokeWidth = " + cercle.StrokeSize + "\n" +
                                          "\t" + paramsName + ".displayGroupParent = " + this.Name.Replace(" ", "") + ".displayGroup\n\n";

                        sb.Append(paramsObj);

                        sb.AppendLine("\t" + paramsName + ".isDraggable = " + obj.CoronaObjectParent.isDraggable.ToString().ToLower());
                        if (obj.CoronaObjectParent.isDraggable == true)
                        {
                            sb.AppendLine("\t" + paramsName + ".dragBody = dragBody");
                            sb.AppendLine("\t" + paramsName + ".dragDamping = " + obj.CoronaObjectParent.DragDamping.ToString().Replace(",", "."));
                            sb.AppendLine("\t" + paramsName + ".dragMaxForce = " + obj.CoronaObjectParent.DragMaxForce);
                            sb.AppendLine("\t" + paramsName + ".dragFrequency = " + obj.CoronaObjectParent.DragFrequency);
                        }

                        String createObj = "\t" + this.Name + "." + objName + " = objectInstance.Object.create(" + paramsName + ")";
                        sb.AppendLine(createObj);

                    }
                    else if (obj.Figure.ShapeType.Equals("LINE"))
                    {
                        //Recuperer le cercle
                        Line line = obj.Figure as Line;

                        //Create table of points
                        string tabPoints = "\tlocal points_" + objName + "= {";
                        for (int k = 0; k < line.Points.Count; k++)
                        {
                            if (k % 50 == 0)
                                tabPoints += "\n\t\t";

                            tabPoints += (((float)line.Points[k].X * XRatio).ToString().Replace(",", ".")) + "," + (((float)line.Points[k].Y * YRatio).ToString().Replace(",", "."));
                            if (k != line.Points.Count - 1)
                                tabPoints += ",";

                        }
                        tabPoints += "\t}";

                        String paramsObj = "\t" + paramsName + ".name = \"" + objName + "\"\n" +
                                                "\t" + paramsName + ".type = \"LINE\"\n" +
                                                "\t" + paramsName + ".isHandledByTilesMap = " + obj.CoronaObjectParent.IsHandledByTilesMap.ToString().ToLower() + "\n" +
                                                 "\t" + paramsName + ".tabPoints = points_" + objName + "\n" +
                                                 "\t" + paramsName + ".rotation = " + obj.Rotation + "\n" +
                                                 "\t" + paramsName + ".blendMode = \"" + obj.blendMode + "\"\n" +
                                                 "\t" + paramsName + ".alpha = " + obj.Alpha.ToString().Replace(",", ".") + "\n" +
                                                  "\t" + paramsName + ".gradient = " + gradient + "\n" +
                                                 "\t" + paramsName + ".backColor = { R = " + line.StrokeColor.R + ",G = " + line.StrokeColor.G + ", B = " + line.StrokeColor.B + "}\n" +
                                                 "\t" + paramsName + ".strokeWidth = " + line.StrokeSize + "\n" +
                                                 "\t" + paramsName + ".displayGroupParent = " + this.Name.Replace(" ", "") + ".displayGroup\n\n";

                        sb.Append(tabPoints);
                        sb.Append(paramsObj);

                        sb.AppendLine("\t" + paramsName + ".isDraggable = " + obj.CoronaObjectParent.isDraggable.ToString().ToLower());
                        if (obj.CoronaObjectParent.isDraggable == true)
                        {
                            sb.AppendLine("\t" + paramsName + ".dragBody = dragBody");
                            sb.AppendLine("\t" + paramsName + ".dragDamping = " + obj.CoronaObjectParent.DragDamping.ToString().Replace(",", "."));
                            sb.AppendLine("\t" + paramsName + ".dragMaxForce = " + obj.CoronaObjectParent.DragMaxForce);
                            sb.AppendLine("\t" + paramsName + ".dragFrequency = " + obj.CoronaObjectParent.DragFrequency);
                        }

                        String createObj = "\t" + this.Name + "." + objName + " = objectInstance.Object.create(" + paramsName + ")";
                        sb.AppendLine(createObj);

                    }
                    else if (obj.Figure.ShapeType.Equals("CURVE"))
                    {
                        //Recuperer le cercle
                        CourbeBezier courbe = obj.Figure as CourbeBezier;

                        GraphicsPath path = new GraphicsPath(FillMode.Winding);
                        path.AddCurve(courbe.UserPoints.ToArray());
                        path.Flatten();
                        PointF[] finalPoints = path.PathPoints;

                        //Create table of points
                        string tabPoints = "\tlocal points_" + objName + "= {";
                        for (int k = 0; k < finalPoints.Length; k++)
                        {
                            if (k % 10 == 0)
                                tabPoints += "\n\t\t";

                            tabPoints += ((float)finalPoints[k].X * XRatio).ToString().Replace(",", ".") + "," + ((float)finalPoints[k].Y * YRatio).ToString().Replace(",", ".");
                            if (k != finalPoints.Length - 1)
                                tabPoints += ",";

                        }
                        tabPoints += "\t}\n";

                        String paramsObj = "\t" + paramsName + ".name = \"" + objName + "\"\n" +
                                              "\t" + paramsName + ".type = \"CURVE\"\n" +
                                              "\t" + paramsName + ".isHandledByTilesMap = " + obj.CoronaObjectParent.IsHandledByTilesMap.ToString().ToLower() + "\n" +
                                               "\t" + paramsName + ".tabPoints = points_" + objName + "\n" +
                                                 "\t" + paramsName + ".rotation = " + obj.Rotation + "\n" +
                                                 "\t" + paramsName + ".blendMode = \"" + obj.blendMode + "\"\n" +
                                                 "\t" + paramsName + ".alpha = " + obj.Alpha.ToString().Replace(",", ".") + "\n" +
                                                  "\t" + paramsName + ".gradient = " + gradient + "\n" +
                                                 "\t" + paramsName + ".backColor = { R = " + courbe.StrokeColor.R + ",G = " + courbe.StrokeColor.G + ", B = " + courbe.StrokeColor.B + "}\n" +
                                                  "\t" + paramsName + ".strokeWidth = " + courbe.StrokeSize + "\n" +
                                                  "\t" + paramsName + ".displayGroupParent = " + this.Name.Replace(" ", "") + ".displayGroup\n\n";

                        sb.Append(tabPoints);

                        sb.Append(paramsObj);

                        sb.AppendLine("\t" + paramsName + ".isDraggable = " + obj.CoronaObjectParent.isDraggable.ToString().ToLower());
                        if (obj.CoronaObjectParent.isDraggable == true)
                        {
                            sb.AppendLine("\t" + paramsName + ".dragBody = dragBody");
                            sb.AppendLine("\t" + paramsName + ".dragDamping = " + obj.CoronaObjectParent.DragDamping.ToString().Replace(",", "."));
                            sb.AppendLine("\t" + paramsName + ".dragMaxForce = " + obj.CoronaObjectParent.DragMaxForce);
                            sb.AppendLine("\t" + paramsName + ".dragFrequency = " + obj.CoronaObjectParent.DragFrequency);
                        }

                        String createObj = "\t" + this.Name + "." + objName + " = objectInstance.Object.create(" + paramsName + ")";
                        sb.AppendLine(createObj);

                    }
                    else if (obj.Figure.ShapeType.Equals("TEXT"))
                    {
                        //Recuperer le cercle
                        Texte text = obj.Figure as Texte;
                        if (text.font2.FontItem == null) text.font2.FontItem = new GameEditor.FontManager.FontItem("DEFAULT", this.SceneParent.projectParent);
                        if (!text.font2.FontItem.NameForAndroid.Equals("DEFAULT"))
                        {
                            string fontDeclaration = text.font2.FontItem.GenerateCode();
                            sb.AppendLine(fontDeclaration);
                        }
                        else
                        {
                            sb.AppendLine("\tlocal font = nil");
                        }

                        String paramsObj = "\t" + paramsName + ".name = \"" + objName + "\"\n" +
                                               "\t" + paramsName + ".type = \"TEXT\" \n" +
                                               "\t" + paramsName + ".isHandledByTilesMap = " + obj.CoronaObjectParent.IsHandledByTilesMap.ToString().ToLower() + "\n" +
                                               "\t" + paramsName + ".x = " + ((float)text.Position.X * XRatio).ToString().Replace(",", ".") + "\n" +
                                               "\t" + paramsName + ".y = " + ((float)text.Position.Y * YRatio).ToString().Replace(",", ".") + "\n" +
                                               "\t" + paramsName + ".width = " + ((float)obj.SurfaceRect.Width * XRatio).ToString().Replace(",", ".") + "\n" +
                                               "\t" + paramsName + ".height = "+((float)0 * YRatio).ToString().Replace(",", ".") + "\n" +
                                               "\t" + paramsName + ".text = \"" + @text.Txt.Replace("\r\n",@"\n").Replace("\"","\\\"") + "\"\n" +
                                                 "\t" + paramsName + ".rotation = " + obj.Rotation + "\n" +
                                                 "\t" + paramsName + ".blendMode = \"" + obj.blendMode + "\"\n" +
                                                 "\t" + paramsName + ".alpha = " + obj.Alpha.ToString().Replace(",", ".") + "\n" +
                                                 "\t" + paramsName + ".gradient = " + gradient + "\n" +
                                                "\t" + paramsName + ".textColor = { R = " + text.FillColor.R + ",G = " + text.FillColor.G + ", B = " + text.FillColor.B + "}\n" +
                                                "\t" + paramsName + ".textSize = " + (((float)text.font2.Size * 1.4f) * XRatio).ToString().Replace(",", ".") + "\n" +
                                                "\t" + paramsName + ".textFont = font\n" +
                                                "\t" + paramsName + ".displayGroupParent = " + this.Name.Replace(" ", "") + ".displayGroup\n\n";

                        sb.Append(paramsObj);

                        sb.AppendLine("\t" + paramsName + ".isDraggable = " + obj.CoronaObjectParent.isDraggable.ToString().ToLower());
                        if (obj.CoronaObjectParent.isDraggable == true)
                        {
                            sb.AppendLine("\t" + paramsName + ".dragBody = dragBody");
                            sb.AppendLine("\t" + paramsName + ".dragDamping = " + obj.CoronaObjectParent.DragDamping.ToString().Replace(",", "."));
                            sb.AppendLine("\t" + paramsName + ".dragMaxForce = " + obj.CoronaObjectParent.DragMaxForce);
                            sb.AppendLine("\t" + paramsName + ".dragFrequency = " + obj.CoronaObjectParent.DragFrequency);
                        }

                        String createObj = "\t" + this.Name + "." + objName + " = objectInstance.Object.create(" + paramsName + ")";
                        sb.AppendLine(createObj);

                    }

                }

                //Ajouter l'object dans les interactions de la tilesmap si elle existe dans le layer
                if (this.TilesMap != null && obj.CoronaObjectParent.IsHandledByTilesMap == true)
                {
                    if (this.TilesMap.isEnabled == true)
                    {
                        sb.AppendLine("\t" + this.Name + "." + this.TilesMap.TilesMapName + ":addExternalObjectToInteractWith(" + objName + ")");
                    }
                }

                //CREER Le mask DE L OBJET SI ELLE EXISTE -----------------------------------------
                if (obj.CoronaObjectParent.BitmapMask != null && obj.CoronaObjectParent.BitmapMask.MaskImage != null && obj.CoronaObjectParent.BitmapMask.IsMaskEnabled == true)
                {
                    sb.AppendLine("\tlocal " + objName + "_mask = graphics.newMask(\"" + objName.ToLower() + "_mask.png\")");
                    sb.AppendLine("\t" + this.Name + "." + objName + ".object:setMask(" + objName + "_mask)");
                }

                //CREER LA PHYSIC DE L OBJET SI ELLE EXISTE -----------------------------------------
                if (obj.CoronaObjectParent.PhysicsBody != null)
                {
                    PhysicsBody ph = obj.CoronaObjectParent.PhysicsBody;
                    if (ph.Mode != PhysicsBody.PhysicBodyMode.Inactive)
                    {
                        CoronaObject coronaObject = obj.CoronaObjectParent;

                        ////Creer le fichier lua associé
                        //PhysicBodyLuaGenerator gen = new PhysicBodyLuaGenerator(coronaObject.PhysicsBody);
                        //gen.writeToLua(new DirectoryInfo(this.SceneParent.projectParent.BuildFolderPath), XRatio, YRatio);

                        //if(File.Exists(this.SceneParent.projectParent.SourceFolderPath+"\\body" + objName.ToLower()+".lua"))
                        //    File.Delete(this.SceneParent.projectParent.SourceFolderPath+"\\body" + objName.ToLower()+".lua");

                        //Faire le require correspondant
                        sb.AppendLine("\tlocal body_" + objName + " = require(\"body" + objName.ToLower() + "\")" + ".startBody(" + this.Name + "." + objName + ")");

                    }

                }

                //CREER Le PATH FOLLOW DE L OBJET SI ELLE EXISTE -----------------------------------------
                if (obj.CoronaObjectParent.PathFollow != null)
                {
                    PathFollow path = obj.CoronaObjectParent.PathFollow;
                    if (path.isEnabled == true)
                    {
                        CoronaObject coronaObject = obj.CoronaObjectParent;

                        sb.AppendLine("\tlocal " + objName + "_pathFollow = " + path.getPointsTableLua(XRatio, YRatio));
                        sb.AppendLine("\tlocal " + objName + "_pathFollow_params = {}");
                        sb.AppendLine("\t" + objName + "_pathFollow_params.isCyclic = " + coronaObject.PathFollow.isCyclic.ToString().ToLower());
                        sb.AppendLine("\t" + objName + "_pathFollow_params.removeOnComplete = " + coronaObject.PathFollow.removeOnComplete.ToString().ToLower());
                        sb.AppendLine("\t" + objName + "_pathFollow_params.rotate = " + coronaObject.PathFollow.Rotate.ToString().ToLower());
                        sb.AppendLine("\t" + objName + "_pathFollow_params.targetObject = " + this.Name + "." + objName);
                        sb.AppendLine("\t" + objName + "_pathFollow_params.path = " + objName + "_pathFollow");
                        sb.AppendLine("\t" + objName + "_pathFollow_params.speed = " + coronaObject.PathFollow.speed);
                        sb.AppendLine("\t" + objName + "_pathFollow_params.iteration = " + coronaObject.PathFollow.Iteration);
                        sb.AppendLine("\t" + this.Name + "." + objName + ".pathFollow = pathFollowInstance.PathFollow.create(" + objName + "_pathFollow_params)");

                    }

                }

                /*  sb.AppendLine("\t" + this.Name + "." + objName + ":setOnStartBehaviour(" + obj.CoronaObjectParent.onStartFunction + ")");
                  sb.AppendLine("\t" + this.Name + "." + objName + ":setOnPauseBehaviour(" + obj.CoronaObjectParent.onPauseFunction + ")");
                  sb.AppendLine("\t" + this.Name + "." + objName + ":setOnDeleteBehaviour(" + obj.CoronaObjectParent.onDeleteFunction + ")");*/

            }
        }
        protected override void OnPaint(PaintEventArgs e)
        {
            #region Declare the internal variables

            SolidBrush bSolid = null;
            LinearGradientBrush bGradient = null;
            Pen p;
            Bitmap bmp;
            Graphics g;
            GraphicsPath gpTitlePath, gpRegion;
            Rectangle rectTopArea, rectBottomArea;
            Rectangle rectLeftCorner, rectRightCorner;
            Rectangle rectTitleBar/*, rectTitleIcon*/;
            StringFormat sf;
            SizeF sizeTitleText;
            Size sizeTitleBar, sizeTitleBody;

            #endregion

            #region Initialize the common variables

            // Create a new Bitmap object
            bmp = new Bitmap(this.Width, this.Height);

            // Initialize the Form Graphics instance
            g = Graphics.FromImage(bmp);
            g.SmoothingMode = SmoothingMode.HighSpeed;
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.InterpolationMode = InterpolationMode.High;

            // Create a new Brush object
            bSolid = new SolidBrush(this.transparentColor);

            // Fill all the area with pink (will be used to create the transparent region)
            g.FillRectangle(bSolid, 0, 0, this.Width, this.Height);

            // Dispose the Brush object
            bSolid.Dispose();
            bSolid = null;

            // Create the rectangles that will be used to round the corners of the form
            rectLeftCorner  = new Rectangle(0, 0, (edgeRadius * 2), (edgeRadius * 2));
            rectRightCorner = new Rectangle(this.Width - (edgeRadius * 2) - 1, 0, (edgeRadius * 2), (edgeRadius * 2));

            // Create the remaining rectangles to complete the form
            rectTopArea    = new Rectangle(edgeRadius, 0, this.Width - (edgeRadius * 2), this.Height);
            rectBottomArea = new Rectangle(0, edgeRadius, this.Width, this.Height);

            #endregion

            #region Calculate the TitleBar and Body dimensions

            sizeTitleText = g.MeasureString(this.Text, this.TitleFont);
            sizeTitleBar = new Size(0, 0);
            sizeTitleBar.Width = this.Width;
            sizeTitleBar.Height = Convert.ToInt32(sizeTitleText.Height) + (padding * 2);

            if (this.Icon != null && sizeTitleBar.Height < 16 + (padding * 2))
            {
                sizeTitleBar.Height = 16 + (padding * 2);
            }

            sizeTitleBody = new Size(0, 0);
            sizeTitleBody.Width = this.Width;
            sizeTitleBody.Height = this.Height - sizeTitleBar.Height;

            rectTitleBar = new Rectangle(0, 0, sizeTitleBar.Width, sizeTitleBar.Height);
            rectBody     = new Rectangle(0, sizeTitleBar.Height, sizeTitleBody.Width, sizeTitleBody.Height);

            #endregion

            #region Draw the TitleBar background color

            // Create a GraphicsPath instance to map our form title shape
            gpTitlePath = new GraphicsPath();
            gpTitlePath.AddArc(rectLeftCorner, 180, 90);
            gpTitlePath.AddArc(rectRightCorner, 270, 90);

            GraphicsPath gTitlePath2 = new GraphicsPath();
            gTitlePath2.AddRectangle(new Rectangle(0, edgeRadius, rectTitleBar.Width - 1, rectTitleBar.Height));
            gTitlePath2.AddPath(gpTitlePath, true);
            gTitlePath2.Flatten();

            if (this.TitleStyle == ColorStyle.Solid)
            {
                // Create a new Brush object
                bSolid = new SolidBrush(this.TitleForeColor);

                // Fill the title area
                g.FillPath(bSolid, gTitlePath2);

                // Dispose the Brush object
                bSolid.Dispose();
                bSolid = null;
            }
            else
            {
                    switch (this.TitleStyle)
                    {
                        case ColorStyle.BackwardDiagonalGradient :
                            // Create a new Brush object
                            bGradient = new LinearGradientBrush(rectTitleBar, this.TitleForeColor, this.TitleBackColor, LinearGradientMode.BackwardDiagonal);
                            break;

                        case ColorStyle.ForwardDiagonalGradient :
                            // Create a new Brush object
                            bGradient = new LinearGradientBrush(rectTitleBar, this.TitleForeColor, this.TitleBackColor, LinearGradientMode.ForwardDiagonal);
                            break;

                        case ColorStyle.HorizontalGradient :
                            // Create a new Brush object
                            bGradient = new LinearGradientBrush(rectTitleBar, this.TitleForeColor, this.TitleBackColor, LinearGradientMode.Horizontal);
                            break;

                        case ColorStyle.VerticalGradient :
                            // Create a new Brush object
                            bGradient = new LinearGradientBrush(rectTitleBar, this.TitleForeColor, this.TitleBackColor, LinearGradientMode.Vertical);
                            break;
                    }

                g.FillPath(bGradient, gTitlePath2);

                // Dispose the LinearGradientBrush object
                bGradient.Dispose();
                bGradient = null;
            }

            #endregion

            #region Draw the Title icons and text

            // Draw the Title icon and text
            bSolid = new SolidBrush(this.TitleColor);
            sf = new StringFormat();
            sf.Alignment =  StringAlignment.Near;
            sf.FormatFlags = StringFormatFlags.NoWrap;
            sf.Trimming = StringTrimming.None;

            rectTitleArea = new Rectangle(0, 0, 0, 0);
            rectTitleArea.X = edgeRadius / 2 + padding;
            rectTitleArea.Y = Convert.ToInt32((rectTitleBar.Height - sizeTitleText.Height) / 2);
            rectTitleArea.Width = this.Width - (edgeRadius * 2) - padding;
            rectTitleArea.Height = padding + Convert.ToInt32(sizeTitleText.Height);

            #region Draw the Application icon

            // commented out because it generated an unreachable code warning
            //if (this.Icon != null && 1 == 2)
            //{
            //    if (this.bmpIcon == null)
            //    {
            //        bmpIcon = this.Icon.ToBitmap();
            //    }

            //    rectTitleIcon = new Rectangle(0, 0, 0, 0);
            //    rectTitleIcon.X = edgeRadius / 2 + padding;
            //    rectTitleIcon.Y = Convert.ToInt32((rectTitleBar.Height - sizeTitleText.Height) / 2);
            //    rectTitleIcon.Width = 16;
            //    rectTitleIcon.Height = 16;

            //    g.SmoothingMode = SmoothingMode.HighQuality;
            //    g.DrawImage(bmpIcon, rectTitleIcon, 0, 0, 32,32, GraphicsUnit.Pixel);
            //    g.SmoothingMode = SmoothingMode.None;

            //    // Compensate for the space taken by the icon image
            //    rectTitleArea.X = rectTitleArea.X  + 16 + padding;
            //}

            #endregion

            #region Draw the Close icon

            rectCloseIcon = new Rectangle(0, 0, 0, 0);
            rectCloseIcon.X = this.Width - edgeRadius - padding - 16 + 2;
            rectCloseIcon.Y = Convert.ToInt32((rectTitleBar.Height - sizeTitleText.Height) / 2) + 2;
            rectCloseIcon.Width = 16 - 2;
            rectCloseIcon.Height = 16 - 2;

            // Create a new Pen object
            if (this.onCloseIcon == false)
                p = new Pen(this.IconsNormalColor, 1);
            else
                p = new Pen(this.IconsHiLiteColor, 1);

            g.DrawLine(p, rectCloseIcon.X + 1, rectCloseIcon.Y, rectCloseIcon.X + rectCloseIcon.Width - 1, rectCloseIcon.Y);
            g.DrawLine(p, rectCloseIcon.X, rectCloseIcon.Y + 1, rectCloseIcon.X, rectCloseIcon.Y + rectCloseIcon.Height - 1);
            g.DrawLine(p, rectCloseIcon.X + rectCloseIcon.Width, rectCloseIcon.Y + 1, rectCloseIcon.X + rectCloseIcon.Width, rectCloseIcon.Y + rectCloseIcon.Height - 1);
            g.DrawLine(p, rectCloseIcon.X + 1, rectCloseIcon.Y + rectCloseIcon.Height, rectCloseIcon.X + rectCloseIcon.Width - 1, rectCloseIcon.Y + rectCloseIcon.Height);

            // Dispose the Pen object
            p.Dispose();
            p = null;

            // Create a new Pen object
            if (this.onCloseIcon == false)
                p = new Pen(this.IconsNormalColor, 2);
            else
                p = new Pen(this.IconsHiLiteColor, 2);

            g.DrawLine(p, rectCloseIcon.X + 3, rectCloseIcon.Y + 3, rectCloseIcon.X + rectCloseIcon.Width - 3, rectCloseIcon.Y + rectCloseIcon.Height - 3);
            g.DrawLine(p, rectCloseIcon.X + rectCloseIcon.Width - 3, rectCloseIcon.Y + 3, rectCloseIcon.X + 3, rectCloseIcon.Y + rectCloseIcon.Height - 3);

            rectCloseIcon.Width += 1;
            rectCloseIcon.Height += 1;

            #endregion

            #region Draw the Minimize icon

            rectMinimizeIcon = new Rectangle(0, 0, 0, 0);
            rectMinimizeIcon.X = this.Width - edgeRadius - (padding * 2) - (16 * 2) + 2;
            rectMinimizeIcon.Y = Convert.ToInt32((rectTitleBar.Height - sizeTitleText.Height) / 2) + 2;
            rectMinimizeIcon.Width = 16 - 2;
            rectMinimizeIcon.Height = 16 - 2;

            // Create a new Pen object
            if (this.onMinimizeIcon == false)
                p = new Pen(this.IconsNormalColor, 1);
            else
                p = new Pen(this.IconsHiLiteColor, 1);

            g.DrawLine(p, rectMinimizeIcon.X + 1, rectMinimizeIcon.Y, rectMinimizeIcon.X + rectMinimizeIcon.Width - 1, rectMinimizeIcon.Y);
            g.DrawLine(p, rectMinimizeIcon.X, rectMinimizeIcon.Y + 1, rectMinimizeIcon.X, rectMinimizeIcon.Y + rectMinimizeIcon.Height - 1);
            g.DrawLine(p, rectMinimizeIcon.X + rectMinimizeIcon.Width, rectMinimizeIcon.Y + 1, rectMinimizeIcon.X + rectMinimizeIcon.Width, rectMinimizeIcon.Y + rectMinimizeIcon.Height - 1);
            g.DrawLine(p, rectMinimizeIcon.X + 1, rectMinimizeIcon.Y + rectMinimizeIcon.Height, rectMinimizeIcon.X + rectMinimizeIcon.Width - 1, rectMinimizeIcon.Y + rectMinimizeIcon.Height);

            // Dispose the Pen object
            p.Dispose();
            p = null;

            // Create a new Pen object
            if (this.onMinimizeIcon == false)
                p = new Pen(this.IconsNormalColor, 2);
            else
                p = new Pen(this.IconsHiLiteColor, 2);

            g.DrawLine(p, rectMinimizeIcon.X + 3, rectMinimizeIcon.Y + rectMinimizeIcon.Height - 3, rectMinimizeIcon.X + rectMinimizeIcon.Width - 2, rectMinimizeIcon.Y + rectMinimizeIcon.Height - 3);

            rectMinimizeIcon.Width += 1;
            rectMinimizeIcon.Height += 1;

            #endregion

            // Compensate for the space taken by the icon image
            rectTitleArea.Width = rectTitleArea.Width - 50;

            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.DrawString(this.Text, this.TitleFont, bSolid, rectTitleArea, sf);
            g.SmoothingMode = SmoothingMode.None;

            // Make sure that TitleArea Rectangle values covers the whole title area
            rectTitleArea.X = 0;
            rectTitleArea.Y = 0;
            rectTitleArea.Width = this.Width;

            // Dispose the StringFormat object
            sf.Dispose();
            sf = null;

            // Dispose the Brush object
            bSolid.Dispose();
            bSolid = null;

            #endregion

            #region Draw the Body background color

            if (this.windowMaximized == true)
            {
                if (this.BodyStyle == ColorStyle.Solid)
                {
                    // Create a new Brush object
                    bSolid = new SolidBrush(this.BodyForeColor);

                    // Fill the body area
                    g.FillRectangle(bSolid, rectBody);

                    // Dispose the Brush object
                    bSolid.Dispose();
                    bSolid = null;
                }
                else
                {
                    switch (this.BodyStyle)
                    {
                        case ColorStyle.BackwardDiagonalGradient :
                            // Create a new Brush object
                            bGradient = new LinearGradientBrush(rectBody, this.BodyForeColor, this.BodyBackColor, LinearGradientMode.BackwardDiagonal);
                            break;

                        case ColorStyle.ForwardDiagonalGradient :
                            // Create a new Brush object
                            bGradient = new LinearGradientBrush(rectBody, this.BodyForeColor, this.BodyBackColor, LinearGradientMode.ForwardDiagonal);
                            break;

                        case ColorStyle.HorizontalGradient :
                            // Create a new Brush object
                            bGradient = new LinearGradientBrush(rectBody, this.BodyForeColor, this.BodyBackColor, LinearGradientMode.Horizontal);
                            break;

                        case ColorStyle.VerticalGradient :
                            // Create a new Brush object
                            bGradient = new LinearGradientBrush(rectBody, this.BodyForeColor, this.BodyBackColor, LinearGradientMode.Vertical);
                            break;
                    }

                    // Fill the body area
                    g.FillRectangle(bGradient, rectBody);

                    // Dispose the LinearGradientBrush object
                    bGradient.Dispose();
                    bGradient = null;
                }
            }

            #endregion

            #region Draw the Resizable symbol

            if (this.IsResizable == true && this.windowMaximized == true)
            {
                rectResizableArea = new Rectangle(0, 0, 0, 0);
                rectResizableArea.X = this.Width - padding - 11;
                rectResizableArea.Y = this.Height - padding - 11;
                rectResizableArea.Height = padding + 11;
                rectResizableArea.Width = padding + 11;

                // Create a new Pen object
                p = new Pen(this.ResizableColor, 2);

                // Draw the resizable symbol
                g.DrawLine(p, this.Width - padding - 11, this.Height - padding, this.Width - padding, this.Height - padding - 11);
                g.DrawLine(p, this.Width - padding - 7, this.Height - padding, this.Width - padding, this.Height - padding - 7);
                g.DrawLine(p, this.Width - padding - 3, this.Height - padding, this.Width - padding, this.Height - padding - 3);

                // Dispose the Pen object
                p.Dispose();
                p = null;
            }

            #endregion

            #region Draw the Form Outline

            // Create a new Pen object
            p = new Pen(this.OutlineColor, this.OutlineSize);

            // Draw the form outline
            g.DrawArc(p, rectLeftCorner, 180, 90);
            g.DrawArc(p, rectRightCorner, 270, 90);
            g.DrawLine(p, edgeRadius, 0, this.Width - edgeRadius, 0);
            g.DrawLine(p, 0, edgeRadius, 0, this.Height);
            g.DrawLine(p, this.Width - 1, edgeRadius, this.Width - 1, this.Height);
            g.DrawLine(p, 0, this.Height - 1, this.Width, this.Height - 1);

            // Dispose the Pen object
            p.Dispose();
            p = null;

            #endregion

            #region Create/Apply a transparent region

            if (this.Region != null)
            {
                this.Region.Dispose();
                this.Region = null;
            }

            // Create GraphicsPath to be used to crop the region required
            gpRegion = new GraphicsPath();

            // Loop through every pixel in the top left corner.
            // Create a 1 x 1 rectangle regions of pixels that do not match the transparent color
            for (int x = rectLeftCorner.X; x < rectLeftCorner.Width; x++)
            {
                for (int y = rectLeftCorner.Y; y < rectLeftCorner.Height / 2; y++)
                {
                    if (isSameColor(bmp.GetPixel(x, y), this.transparentColor) == false)
                    {
                        gpRegion.AddRectangle(new Rectangle(x, y, 1, 1));
                    }
                }
            }

            // Loop through every pixel in the top right corner.
            // Create a 1 x 1 rectangle regions of pixels that do not match the transparent color
            for (int x = rectRightCorner.X + 1; x < rectRightCorner.X + rectRightCorner.Width + 1; x++)
            {
                for (int y = rectRightCorner.Y; y < rectRightCorner.Y + rectRightCorner.Height / 2; y++)
                {
                    if (isSameColor(bmp.GetPixel(x, y), this.transparentColor) == false)
                    {
                        gpRegion.AddRectangle(new Rectangle(x, y, 1, 1));
                    }
                }
            }

            // Create the remaining rectangular regions to complete cover all the windows form area
            gpRegion.AddRectangle(new Rectangle(rectLeftCorner.Width, 0, this.Width - (edgeRadius * 4), rectLeftCorner.Height / 2));
            gpRegion.AddRectangle(new Rectangle(0, rectLeftCorner.Height / 2, this.Width, this.Height));

            // Apply region
            this.Region = new Region(gpRegion);

            #endregion

            #region Draw the buffered image on the windows form Graphics object

            // Draw the buffered image on the windows form Graphics object
            e.Graphics.DrawImageUnscaled(bmp, 0, 0, this.Width, this.Height);

            // Dispose the Graphics object
            g.Dispose();
            g = null;

            // Dispose the Bitmap object
            bmp.Dispose();
            bmp = null;

            #endregion
        }
Пример #19
0
        private void Flatten1(Graphics g)
        {
            GraphicsPath myPath = new GraphicsPath();
            Matrix translateMatrix = new Matrix();
            translateMatrix.Translate(0, 10);
            Point point1 = new Point(20, 120);
            Point point2 = new Point(70, 30);
            Point point3 = new Point(130, 220);
            Point point4 = new Point(180, 120);
            Point[] points = {point1, point2, point3, point4};
            myPath.AddCurve(points);

            g.DrawPath(new Pen(Color.Black, 1), myPath);

            var pathPoints = myPath.PathPoints;
            var pathTypes = myPath.PathTypes;

            Console.WriteLine("Flatten before Flattening");
            for (int i = 0; i < myPath.PathTypes.Length; i++)
            {
                Console.WriteLine("{0} - {1},{2}", (PathPointType)pathTypes[i], pathPoints[i].X, pathPoints[i].Y);
            }

            myPath.Flatten(translateMatrix, 10);

            pathPoints = myPath.PathPoints;
            pathTypes = myPath.PathTypes;

            Console.WriteLine("Flatten after Flattening");
            for (int i = 0; i < myPath.PathTypes.Length; i++)
            {
                Console.WriteLine("{0} - {1},{2}", (PathPointType)pathTypes[i], pathPoints[i].X, pathPoints[i].Y);
            }

            g.DrawPath(new Pen(Color.Red, 1), myPath);
        }
Пример #20
0
		public void Flatten_Rectangle ()
		{
			GraphicsPath path = new GraphicsPath ();
			path.AddRectangle (new Rectangle (0, 0, 100, 100));
			GraphicsPath clone = (GraphicsPath) path.Clone ();
			path.Flatten ();
			ComparePaths (path, clone);
		}
Пример #21
0
        public IEnumerable<MapObject> Create(IDGenerator generator, Box box, ITexture texture, int roundDecimals)
        {
            var width = box.Width;
            var length = Math.Max(1, Math.Abs((int) box.Length));
            var height = box.Height;
            var flatten = (float) _flattenFactor.Value;
            var text = _text.GetValue();

            var family = _fontChooser.GetFontFamily();
            var style = Enum.GetValues(typeof (FontStyle)).OfType<FontStyle>().FirstOrDefault(fs => family.IsStyleAvailable(fs));
            if (!family.IsStyleAvailable(style)) family = FontFamily.GenericSansSerif;

            var set = new PolygonSet();

            var sizes = new List<RectangleF>();
            using (var bmp = new Bitmap(1,1))
            {
                using (var g = System.Drawing.Graphics.FromImage(bmp))
                {
                    using (var font = new Font(family, length, style, GraphicsUnit.Pixel))
                    {
                        for (var i = 0; i < text.Length; i += 32)
                        {
                            using (var sf = new StringFormat(StringFormat.GenericTypographic))
                            {
                                var rem = Math.Min(text.Length, i + 32) - i;
                                var range = Enumerable.Range(0, rem).Select(x => new CharacterRange(x, 1)).ToArray();
                                sf.SetMeasurableCharacterRanges(range);
                                var reg = g.MeasureCharacterRanges(text.Substring(i, rem), font, new RectangleF(0, 0, float.MaxValue, float.MaxValue), sf);
                                sizes.AddRange(reg.Select(x => x.GetBounds(g)));
                            }
                        }
                    }
                }
            }

            var xOffset = box.Start.DX;
            var yOffset = box.End.DY;

            for (var ci = 0; ci < text.Length; ci++)
            {
                var c = text[ci];
                var size = sizes[ci];

                var gp = new GraphicsPath();
                gp.AddString(c.ToString(CultureInfo.InvariantCulture), family, (int)style, length, new PointF(0, 0), StringFormat.GenericTypographic);
                gp.Flatten(new System.Drawing.Drawing2D.Matrix(), flatten);

                var polygons = new List<Polygon>();
                var poly = new List<PolygonPoint>();

                for (var i = 0; i < gp.PointCount; i++)
                {
                    var type = gp.PathTypes[i];
                    var point = gp.PathPoints[i];

                    poly.Add(new PolygonPoint(point.X + xOffset, -point.Y + yOffset));

                    if ((type & 0x80) == 0x80)
                    {
                        polygons.Add(new Polygon(poly));
                        poly.Clear();
                    }
                }

                var tri = new List<Polygon>();
                Polygon polygon = null;
                foreach (var p in polygons)
                {
                    if (polygon == null)
                    {
                        polygon = p;
                        tri.Add(p);
                    }
                    else if (p.CalculateWindingOrder() != polygon.CalculateWindingOrder())
                    {
                        polygon.AddHole(p);
                    }
                    else
                    {
                        polygon = null;
                        tri.Add(p);
                    }
                }

                foreach (var pp in tri)
                {
                    try
                    {
                        P2T.Triangulate(pp);
                        set.Add(pp);
                    }
                    catch
                    {
                        // Ignore
                    }
                }

                xOffset += size.Width;
            }

            var zOffset = box.Start.Z;

            foreach (var polygon in set.Polygons)
            {
                foreach (var t in polygon.Triangles)
                {
                    var points = t.Points.Select(x => new Coordinate((decimal) x.X, (decimal) x.Y, zOffset).Round(roundDecimals)).ToList();

                    var faces = new List<Coordinate[]>();

                    // Add the vertical faces
                    var z = new Coordinate(0, 0, height).Round(roundDecimals);
                    for (var j = 0; j < points.Count; j++)
                    {
                        var next = (j + 1) % points.Count;
                        faces.Add(new[] {points[j], points[j] + z, points[next] + z, points[next]});
                    }
                    // Add the top and bottom faces
                    faces.Add(points.ToArray());
                    faces.Add(points.Select(x => x + z).Reverse().ToArray());

                    // Nothing new here, move along
                    var solid = new Solid(generator.GetNextObjectID()) {Colour = Colour.GetRandomBrushColour()};
                    foreach (var arr in faces)
                    {
                        var face = new Face(generator.GetNextFaceID())
                        {
                            Parent = solid,
                            Plane = new Plane(arr[0], arr[1], arr[2]),
                            Colour = solid.Colour,
                            Texture = {Texture = texture}
                        };
                        face.Vertices.AddRange(arr.Select(x => new Vertex(x, face)));
                        face.UpdateBoundingBox();
                        face.AlignTextureToFace();
                        solid.Faces.Add(face);
                    }
                    solid.UpdateBoundingBox();
                    yield return solid;
                }
            }
        }
Пример #22
0
		public void Flatten_NullFloat ()
		{
			GraphicsPath path = new GraphicsPath ();
			GraphicsPath clone = (GraphicsPath) path.Clone ();
			// this is a no-op as there's nothing in the path
			// an no matrix to apply
			path.Flatten (null, 1f);
			ComparePaths (path, clone);
		}
Пример #23
0
		public void Flatten_Arc ()
		{
			GraphicsPath path = new GraphicsPath ();
			path.AddArc (0f, 0f, 100f, 100f, 30, 30);
			GraphicsPath clone = (GraphicsPath) path.Clone ();
			path.Flatten ();
			CompareFlats (path, clone);
		}
        private int getNearestLine(RectangleF hit)
        {
            int result = -1;
            if (LineList.Items.Count == 0) return -1;
            for (int i = 0; i < LineList.Items.Count; i++)
            {
                PointF[] tmp = (Lines[i] as PData).Lines;

                using (GraphicsPath gp = new GraphicsPath())
                {
                    gp.AddLines(tmp);

                    gp.Flatten(null, .1f);
                    tmp = gp.PathPoints;
                    for (int j = 0; j < tmp.Length; j++)
                    {
                        PointF p = new PointF(tmp[j].X * pb.ClientSize.Width,
                        tmp[j].Y * pb.ClientSize.Height);

                        if (hit.Contains(p))
                        {
                            result = i;
                            break;
                        }
                    }
                    if (result > -1) break;
                }
            }
            return result;
        }
Пример #25
0
        static List<PointF> GetArrowLinePoints(float x1, float y1, float x2, float y2, out float centerX, out float centerY, float extra_thickness = 0)
        {
            var widthX	= (x2 - x1);
            var lengthX = Math.Max(60, Math.Abs(widthX / 2))
                //+ Math.Max(0, -widthX / 2)
                ;
            var lengthY = 0;// Math.Max(-170, Math.Min(-120.0f, widthX - 120.0f)) + 120.0f;
            if (widthX < 120)
                lengthX = 60;
            var yB = ((y1 + y2) / 2) + lengthY;// (y2 + ((y1 - y2) / 2) * 0.75f) + lengthY;
            var yC = y2 + yB;
            var xC = (x1 + x2) / 2;
            var xA = x1 + lengthX;
            var xB = x2 - lengthX;

            /*
            if (widthX >= 120)
            {
                xA = xB = xC = x2 - 60;
            }
            //*/

            var points = new List<PointF> {
                new PointF(x1, y1),
                new PointF(xA, y1),
                new PointF(xB, y2),
                new PointF(x2 - GraphConstants.ConnectorSize - extra_thickness, y2)
            };

            var t  = 1.0f;//Math.Min(1, Math.Max(0, (widthX - 30) / 60.0f));
            var yA = (yB * t) + (yC * (1 - t));

            if (widthX <= 120)
            {
                points.Insert(2, new PointF(xB, yA));
                points.Insert(2, new PointF(xC, yA));
                points.Insert(2, new PointF(xA, yA));
            }
            //*
            using (var tempPath = new GraphicsPath())
            {
                tempPath.AddBeziers(points.ToArray());
                tempPath.Flatten();
                points = tempPath.PathPoints.ToList();
            }
            //*/
            var angles	= new PointF[points.Count - 1];
            var lengths = new float[points.Count - 1];
            float totalLength = 0;
            centerX = 0;
            centerY = 0;
            points.Add(points[points.Count - 1]);
            for (int i = 0; i < points.Count - 2; i++)
            {
                var pt1 = points[i];
                var pt2 = points[i + 1];
                var pt3 = points[i + 2];
                var deltaX = (float)((pt2.X - pt1.X) + (pt3.X - pt2.X));
                var deltaY = (float)((pt2.Y - pt1.Y) + (pt3.Y - pt2.Y));
                var length = (float)Math.Sqrt((deltaX * deltaX) + (deltaY * deltaY));
                if (length <= 1.0f)
                {
                    points.RemoveAt(i);
                    i--;
                    continue;
                }
                lengths[i] = length;
                totalLength += length;
                angles[i].X = deltaX / length;
                angles[i].Y = deltaY / length;
            }

            float midLength		= (totalLength / 2.0f);// * 0.75f;
            float startWidth	= extra_thickness + 0.75f;
            float endWidth		= extra_thickness + (GraphConstants.ConnectorSize / 3.5f);
            float currentLength = 0;
            var newPoints = new List<PointF>();
            newPoints.Add(points[0]);
            for (int i = 0; i < points.Count - 2; i++)
            {
                var angle	= angles[i];
                var point	= points[i + 1];
                var length	= lengths[i];
                var width	= (((currentLength * (endWidth - startWidth)) / totalLength) + startWidth);
                var angleX	= angle.X * width;
                var angleY	= angle.Y * width;

                var newLength = currentLength + length;
                if (currentLength	<= midLength &&
                    newLength		>= midLength)
                {
                    var dX = point.X - points[i].X;
                    var dY = point.Y - points[i].Y;
                    var t1 = midLength - currentLength;
                    var l  = length;

                    centerX = points[i].X + ((dX * t1) / l);
                    centerY = points[i].Y + ((dY * t1) / l);
                }

                var pt1 = new PointF(point.X - angleY, point.Y + angleX);
                var pt2 = new PointF(point.X + angleY, point.Y - angleX);
                if (Math.Abs(newPoints[newPoints.Count - 1].X - pt1.X) > 1.0f ||
                    Math.Abs(newPoints[newPoints.Count - 1].Y - pt1.Y) > 1.0f)
                    newPoints.Add(pt1);
                if (Math.Abs(newPoints[0].X - pt2.X) > 1.0f ||
                    Math.Abs(newPoints[0].Y - pt2.Y) > 1.0f)
                    newPoints.Insert(0, pt2);

                currentLength = newLength;
            }

            return newPoints;
        }
Пример #26
0
		public void Flatten_Ellipse ()
		{
			GraphicsPath path = new GraphicsPath ();
			path.AddEllipse (10f, 10f, 100f, 100f);
			GraphicsPath clone = (GraphicsPath) path.Clone ();
			path.Flatten ();
			CompareFlats (path, clone);
		}
Пример #27
0
		/// <summary>
		/// Produces DXF output from various type of lines
		/// </summary>
		/// <param name="pt">Point array of the line points</param>
		/// <param name="crLine">Line color</param>
		/// <param name="LayerName">Name of the layer to place the line</param>
		/// <param name="dlt">Line type according to DxLineType enum</param>
		/// <param name="dash">Line dash style</param>
		/// <param name="LineWidth">Used for bezier curves ( if 8 - points, 16 - controls points )</param>
		/// <returns>DXF output string</returns>
		public string Pt2String(PointF[] pt, Color crLine , string LayerName, DxLineType dlt , DashStyle dash , Single LineWidth )
		{

			string sResult = "";
			bool IsClosedLine = false;
			long SegCount = 0;
			bool FirstOrLast = false;

			try
			{
				// Validating input parameters
				if ( pt == null )
					throw new Exception("Null points array passed");

				if ( pt.Length == 0 )
					throw new Exception("Empty points array passed");

				IsClosedLine = (pt[0] == pt[pt.Length-1]);
				if (( dlt == DxLineType.ltSingle) || (dlt == DxLineType.ltClosedSingle))
					SegCount = pt.Length - 1;
				else
					SegCount = pt.Length;

				// Processing all line points according to its type
				for ( int i=0; i< SegCount ; i++)
				{
					FirstOrLast =((i ==0) || (i == SegCount-1));

					switch ( dlt)
					{

						case DxLineType.ltSingle:
						case DxLineType.ltClosedSingle:
							sResult+=String.Format(provider, "0\nLINE\n  100\nAcDbEntity\n{0:HAN}  8\n{1}\n  6\n{6:DASH_STYLE}\n62\n{0:ACI}\n  100\nAcDbLine\n  10\n{2:U}\n  20\n{3:U}\n  11\n{4:U}\n  21\n{5:U}\n",
								crLine, LayerName, pt[i].X, pt[i].Y, pt[i+1].X, pt[i+1].Y, dash);
						
							break;
						case DxLineType.ltBezier:
						sResult+=String.Format(provider, "  0\nVERTEX\n  100\nAcDbEntity\n{0:HAN}  8\n{2}\n  62\n{4:ACI}\n100\nAcDbVertex\n  100\nAcDb2dVertex\n  10\n{0:U}\n  20\n{1:U}\n  70\n{3}\n", pt[i].X, pt[i].Y, LayerName, 16 , crLine, dash);
							break;

						case DxLineType.ltVertex:
							sResult+=String.Format(provider, "  0\nVERTEX\n  100\nAcDbEntity\n{0:HAN}  8\n{2}\n  62\n{4:ACI}\n100\nAcDbVertex\n  100\nAcDb2dVertex\n  10\n{0:U}\n  20\n{1:U}\n  70\n{3}\n", pt[i].X, pt[i].Y, LayerName, LineWidth, crLine);
							break;
						case DxLineType.ltPoly:
							sResult+=String.Format(provider, "  10\n{0:U}\n  20\n{1:U}\n", pt[i].X, pt[i].Y);
							break;
						case DxLineType.ltHatch:
							sResult+=String.Format(provider, "  10\n{0:U}\n  20\n{1:U}\n", pt[i].X, pt[i].Y);
							break;
						default:
							throw new Exception("Line type is not supported");
					}

					
				}
		
				// Post - processing some types of line
				if  (dlt == DxLineType.ltClosedSingle)
					sResult+=String.Format(provider, "0\nLINE\n  100\nAcDbEntity\n{0:HAN}  8\n{1}\n  6\n{6:DASH_STYLE}\n62\n{0:ACI}\n  100\nAcDbLine\n  10\n{2:U}\n  20\n{3:U}\n  11\n{4:U}\n  21\n{5:U}\n",
						crLine, LayerName, pt[pt.Length - 1].X, pt[pt.Length - 1].Y, pt[0].X, pt[0].Y, dash);
				
				
				if ( dlt == DxLineType.ltPoly )
					sResult = String.Format(provider, "0\nLWPOLYLINE\n  100\nAcDbEntity\n{0:HAN}  8\n{1}\n  6\n{5:DASH_STYLE}\n62\n{0:ACI}\n  100\nAcDbPolyline\n  90\n{2}\n  70\n{4}\n{3}", 
						crLine, LayerName, pt.Length , sResult, IsClosedLine ? "1" : "0", dash);

				
				if ( dlt == DxLineType.ltBezier )
				{
					GraphicsPath gr_temp = new GraphicsPath(FillMode.Winding);
					gr_temp.AddBeziers(pt);

					gr_temp.Flatten();
					PointF[] pts2 = gr_temp.PathData.Points as PointF[];
									
					sResult = String.Format(provider, "0\nPOLYLINE\n{0:HAN}   100\nAcDbEntity\n 8\n{0}\n  6\n{4:DASH_STYLE}\n  62\n{1:ACI}\n  100\nAcDb2dPolyline\n  66\n1\n  70\n4\n  75\n6\n{2}{3}  0\nSEQEND\n  100\nAcDbEntity\n{0:HAN}", 
						LayerName,
						crLine, 
						sResult,
						Pt2String(pts2,crLine,LayerName,DxLineType.ltVertex, dash, 8), dash);

					gr_temp.Dispose();
				}

			}
			catch ( Exception ex)
			{
				sResult = "";
				m_status = ex.Message;
				Trace.WriteLine(String.Format("{0} error {1}\n","DxfHelper.Pt2String",ex.Message));
			}
			
			return sResult;								
		}
Пример #28
0
		public void Flatten_Line ()
		{
			GraphicsPath path = new GraphicsPath ();
			path.AddLine (10f, 10f, 100f, 100f);
			GraphicsPath clone = (GraphicsPath) path.Clone ();
			path.Flatten ();
			ComparePaths (path, clone);
		}
Пример #29
0
		public void Flatten_Curve ()
		{
			GraphicsPath path = new GraphicsPath ();
			path.AddCurve (new Point[4] { 
				new Point (0, 0), new Point (40, 20),
				new Point (20, 40), new Point (40, 40)
				});
			GraphicsPath clone = (GraphicsPath) path.Clone ();
			path.Flatten ();
			CompareFlats (path, clone);
		}
Пример #30
0
        private void DrawText(PointF[] points, int maxPoints)
        {
            GraphicsPath gp = new GraphicsPath(_pathdata.Points, _pathdata.Types) { FillMode = FillMode.Winding };
            gp.Flatten();
            gp.Dispose();
            Graphics g = _graphics;
            GraphicsContainer graphicsContainer = g.BeginContainer();
            //g.TranslateTransform(_graphicsPath.GetBounds().X, _graphicsPath.GetBounds().Y);
            int count = 0;
            PointF point1 = default(PointF);
            int charStep = 0;
            double maxWidthText = default(double);
            int i;

            for (i = 0; i <= _text.Length - 1; i++)
            {
                maxWidthText += StringRegion(g, i);
            }

            switch (_pathalign)
            {
                case TextPathAlign.Left:
                    point1 = points[0];
                    count = 0;
                    break;
                case TextPathAlign.Center:
                    count = (int)((maxPoints - maxWidthText) / 2);
                    if (count > 0)
                    {
                        point1 = points[count];
                    }
                    else
                    {
                        point1 = points[0];
                    }

                    break;
                case TextPathAlign.Right:
                    count = (int)(maxPoints - maxWidthText - (double)StringRegion(g, _text.Length - 1) * LetterSpacePercentage / 100);
                    if (count > 0)
                    {
                        point1 = points[count];
                    }
                    else
                    {
                        point1 = points[0];
                    }

                    break;
            }

            while (!(charStep > _text.Length - 1))
            {
                int lStrWidth = (int)(StringRegion(g, charStep) * LetterSpacePercentage / 100);
                if ((count + lStrWidth / 2) >= 0 & (count + lStrWidth) < maxPoints)
                {
                    count += lStrWidth;
                    PointF point2 = points[count];
                    PointF point = points[count - lStrWidth / 2];
                    double angle = GetAngle(point1, point2);
                    DrawRotatedText(g, _text[charStep].ToString(), (float)angle, point);
                    point1 = points[count];
                }
                else
                {
                    count += lStrWidth;
                }
                charStep += 1;
            }
            g.EndContainer(graphicsContainer);
        }