IntersectsWith() private method

private IntersectsWith ( RectangleF rect ) : bool
rect RectangleF
return bool
コード例 #1
0
 public bool IsVisible(RectangleF rect)
 {
     if (rects.Length > 0 && extent.IntersectsWith(rect))
     {
         for (int i = 0; i < rects.Length; i++)
         {
             RectangleF currentRect = rects[i];
             // Not far enough down yet
             if (currentRect.Bottom <= rect.Top)
             {
                 continue;
             }
             // Too far down
             if (currentRect.Top >= rect.Bottom)
             {
                 break;
             }
             // Not far over enough yet
             if (currentRect.Right <= rect.Left)
             {
                 continue;
             }
             if (currentRect.Left >= rect.Right)
             {
                 continue;
             }
             return(true);
         }
     }
     return(false);
 }
コード例 #2
0
        public static bool DoesLineIntersectRectangle(RectangleF pobjRectangle, Line pobjLine, ref Line pobjIntersectingPortionOfLine)
        {
            RectangleF objLineAsRectangle = default(RectangleF);
            objLineAsRectangle = pobjLine.ToRectangle();

            if (!pobjRectangle.IntersectsWith(objLineAsRectangle))
            {
                return false;
            }
            else
            {
                bool blnIsPointAIn = false;
                bool blnIsPointBIn = false;

                blnIsPointAIn = pobjRectangle.Contains(pobjLine.PointA);
                blnIsPointBIn = pobjRectangle.Contains(pobjLine.PointB);

                if (blnIsPointAIn && blnIsPointBIn)
                {
                    pobjIntersectingPortionOfLine = pobjLine;
                }
                else
                {
                    PointF[] colIntersections = new PointF[2];
                    // Either one or two intersections.
                    List<Line> colLines = null;
                    colLines = GeometryHelper.RectangleTo4Lines(pobjRectangle);

                    foreach (Line objLine in colLines)
                    {
                        if (colIntersections[0].IsEmpty)
                        {
                            DoLinesIntersect(objLine, pobjLine, ref colIntersections[0]);
                        }
                        else if (colIntersections[1].IsEmpty)
                        {
                            DoLinesIntersect(objLine, pobjLine, ref colIntersections[1]);
                        }
                    }

                    if (!blnIsPointAIn && !blnIsPointBIn)
                    {
                        pobjIntersectingPortionOfLine = new Line(colIntersections[0], colIntersections[1]);
                    }
                    else
                    {
                        if (blnIsPointAIn)
                        {
                            pobjIntersectingPortionOfLine = new Line(colIntersections[0], pobjLine.PointA);
                        }
                        else
                        {
                            pobjIntersectingPortionOfLine = new Line(colIntersections[0], pobjLine.PointB);
                        }
                    }
                }

                return true;
            }
        }
コード例 #3
0
ファイル: SelectionHelper.cs プロジェクト: Kagamia/TimeBeam
 /// <summary>
 ///   Check if a given rectangle would be selected by another rectangle.
 ///   By default, checks whether the selection rectangle intersects with the bounding rectangle.
 ///   If Alt is pressed, the selection rectangle has to contain the complete bounding rectangle.
 /// </summary>
 /// <param name="selectionRectangle">The rectangle that represents the selection.</param>
 /// <param name="boundingRectangle">The rectangle that should be tested whether it is selected.</param>
 /// <param name="modifierKeys">The modifier keys that are currently pressed.</param>
 /// <returns>
 ///   <see langword="true" /> if the rectangle is selected; <see langword="false" /> otherwise.
 /// </returns>
 public static bool IsSelected( RectangleF selectionRectangle, RectangleF boundingRectangle, Keys modifierKeys )
 {
     if( ( modifierKeys & Keys.Alt ) != 0 ) {
     return selectionRectangle.Contains( boundingRectangle );
       } else {
     return selectionRectangle.IntersectsWith( boundingRectangle );
       }
 }
コード例 #4
0
        private static bool Collision(Position bullet, Position enemy)
        {
            if (bullet == null || enemy == null) return false;

            var bulletBounding = new RectangleF(new PointF(bullet.X, bullet.Y), new SizeF(1.5f, 1.5f));
            var enemyBounding = new RectangleF(new PointF(enemy.X - 32, enemy.Y - 32), new SizeF(64, 64));

            return bulletBounding.IntersectsWith(enemyBounding);
        }
コード例 #5
0
ファイル: ProfilePictureBox.cs プロジェクト: Corpelijn/SE41A
        protected override void OnMouseClick(MouseEventArgs e)
        {
            base.OnMouseClick(e);

            var mouseRect = new RectangleF(e.X, e.Y, 1, 1);
            if (mouseRect.IntersectsWith(ButtonPlusRect))
            {
                OnPlusButtonClick(e);
            }
        }
コード例 #6
0
        // Creates a new array and copies when we run out of space. Doubles the size.

        // Intersection of reg1 and reg2
        private static void Intersect(Region reg1, Region reg2)
        {
            // Trivial case
            RectangleF reg1Extent = reg1.extent;

            if (reg1.rects.Length == 0 || reg2.rects.Length == 0 || !reg1Extent.IntersectsWith(reg2.extent))
            {
                reg1.MakeEmpty();
                return;
            }
            Region intersect = RegionOperation(reg1, reg2, RegionOperationType.Intersect);

            CalculateExtents(intersect);
            reg1.rects  = intersect.rects;
            reg1.extent = intersect.extent;
        }
コード例 #7
0
        // Subtract reg2 from reg1
        private static Region Subtract(Region reg1, Region reg2)
        {
            RectangleF extent1 = reg1.extent;

            if (reg1.rects.Length == 0 || reg2.rects.Length == 0 || !extent1.IntersectsWith(reg2.extent))
            {
                Region region = new Region();
                region.extent = reg1.extent;
                region.rects  = (RectangleF[])reg1.rects.Clone();
                return(region);
            }
            else
            {
                Region subtract = RegionOperation(reg1, reg2, RegionOperationType.Subtract);
                CalculateExtents(subtract);
                return(subtract);
            }
        }
コード例 #8
0
ファイル: Cluster.cs プロジェクト: nothinggood87/RPGSimAlpha_
 private void RefreshTooFarAway(View view,ref RectangleF windowFrame,bool forceRender = false)
 {
     if (forceRender)
     {
         //TooFarAway = false;
         return;
     }
     Vector2 position = ((PositionTopLeft + (CenterOfMass / (View.MaxTextureSize/View.MaxTextureSize)) - Velocity));
     RectangleF renderFrame = new RectangleF(
         (position.X - ((Width / 2) / view.Zoom)), (position.Y - ((Height / 2) / view.Zoom)),
         (Width / view.Zoom), (Height / view.Zoom));
     if (windowFrame.IntersectsWith(renderFrame))
     {
         TooFarAway = false;
     }
     else
     {
         TooFarAway = true;
     }
 }
コード例 #9
0
ファイル: SlideLayoutVeiw.cs プロジェクト: AlexSneg/VIRD-1.0
        void DrawSegments(Graphics grfx, RectangleF rectClip)
        {
            int penWidth = 3;

            if (LicenseManager.UsageMode == LicenseUsageMode.Runtime)
            {
                //рисование границ кубов
                if (PresentationController.Instance != null && PresentationController.Instance.CurrentSlideLayout != null)
                {
                    ISegmentationSupport disp = PresentationController.Instance.CurrentSlideLayout.Display as ISegmentationSupport;
                    if (disp != null)
                    {
                        float x = 0;
                        float y = 0;
                        List<RectangleF> rects = new List<RectangleF>();
                        for (int i = 0; i < disp.SegmentColumns; ++i)
                        {
                            for (int j = 0; j < disp.SegmentRows; j++)
                            {
                                RectangleF rect = new RectangleF(x, y, disp.SegmentWidth, disp.SegmentHeight);

                                if (rect.IntersectsWith(rectClip))
                                    rects.Add(rect);

                                y += disp.SegmentHeight + penWidth + 1;
                            }

                            x += disp.SegmentWidth + penWidth + 1;
                            y = 0;
                        }

                        if (rects.Count > 0)
                        {
                            Pen p = new Pen(new SolidBrush(Color.FromArgb(180, Color.Indigo)), penWidth);
                            p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
                            grfx.DrawRectangles(p, rects.ToArray());
                        }
                    }
                }
            }
        }
コード例 #10
0
ファイル: FwGraphics.cs プロジェクト: sillsdev/WorldPad
		/// -----------------------------------------------------------------------------------
		/// <summary>Member FwInvertRect</summary>
		/// <param name='xLeft'>xLeft</param>
		/// <param name='yTop'>yTop</param>
		/// <param name='xRight'>xRight</param>
		/// <param name='yBottom'>yBottom</param>
		/// -----------------------------------------------------------------------------------
		public void FwInvertRect(int xLeft, int yTop, int xRight, int yBottom)
		{
			Debug.Assert(m_bitmapGraphics != null);
			RectangleF rc = new RectangleF(xLeft, yTop, xRight - xLeft,
				yBottom - yTop);

			if (!rc.IntersectsWith(m_bitmapGraphics.VisibleClipBounds))
				return;
			rc.Intersect(m_bitmapGraphics.VisibleClipBounds);

			//RectangleF rect = new RectangleF(xLeft, yTop, xRight - xLeft + 1, yBottom - yTop + 1);
			//rect.Intersect(m_bitmapGraphics.VisibleClipBounds);
			//Rectangle rc = new Rectangle(
			//	m_parent.PointToScreen(new Point((int)rect.X, (int)rect.Y)),
			//	new Size((int)rect.Width, (int)rect.Height));

			//ControlPaint.FillReversibleRectangle(rc, m_backColor);


			m_backColor = Color.FromArgb(150, SystemColors.Highlight);
			m_bitmapGraphics.FillRectangle(new SolidBrush(m_backColor), rc);
		}
コード例 #11
0
        protected override System.Drawing.Bitmap PlotarGráfico(int width, int height, System.Collections.IDictionary props)
        {
            Bitmap bmp;		// Imagem a ser construída
            PointF centro;		// Centro do gráfico
            float raio;		// Raio da pizza
            PointF posição;	// Posição do gráfico
            float ânguloY;	// Ângulo/Y
            float porcentoY;	// 100/Y
            bool[] porcentagens;// Quais valores tem sua porcentagem escrita

            porcentagens = new bool[dados.Length];

            // Construir imagem
            bmp = new Bitmap(width, height);

            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;

                if (props["limparFundo"] != null)
                    g.FillRectangle((Brush)props["limparFundo"], 0, 0, bmp.Width, bmp.Height);

                // Determinar o centro
                centro = new PointF(width / 2, height / 2);

                // Determinar o raio
                raio = DeterminarRaioPizza(g, width, height, props);

                // Determinan a posição do gráfico
                posição = new PointF(centro.X - raio / 2, centro.Y - raio / 2);

                // Calcular ângulo por valores e porcentagem
                double soma = 0;

                foreach (double[] vetor in dados)
                    foreach (double valor in vetor)
                        soma += valor;

                ânguloY = (float)(360 / soma);
                porcentoY = (float)(100 / soma);

                // Desenhar o gráfico
                float ânguloAtual = 0;

                for (int seq = 0; seq < dados.Length; seq++)
                {
                    float valor = (float)SomaValores(dados[seq]);
                    float ânguloValor = ânguloY * valor;

                    // Colorir fundo
                    g.FillPie(
                        (Brush)props["seqBrush" + seq.ToString()],
                        posição.X, posição.Y,
                        raio, raio,
                        ânguloAtual,
                        ânguloValor);

                    // Desenhar borda
                    g.DrawPie(
                        new Pen(Color.Black, 1.5f),
                        posição.X, posição.Y,
                        raio, raio,
                        ânguloAtual,
                        ânguloValor);

                    // Área para desenho
                    System.Drawing.Drawing2D.GraphicsPath área = new GraphicsPath();
                    área.AddPie(posição.X, posição.Y, raio, raio, ânguloAtual, ânguloValor);

                    g.Flush(System.Drawing.Drawing2D.FlushIntention.Flush);
                    g.Clip = new Region(área);

                    área.Dispose();

                    // Verificar se é possível escrever a porcentagem dentro da fatia
                    string legenda;
                    SizeF tamanhoLegenda;



                    // Escrever legenda (porcentagem)
                    legenda = Math.Round(porcentoY * valor).ToString() + "%";
                    tamanhoLegenda = g.MeasureString(
                        legenda,
                        (Font)props["legendaFont"]);

                    PointF posiçãoLegenda;

                    float legRaio = raio / 5 - 5;

                    do
                    {
                        legRaio += 5;

                        posiçãoLegenda = new PointF(
                            (float)(centro.X + legRaio * Math.Cos(Math.PI * (ânguloAtual + ânguloValor / 2f) / 180) - tamanhoLegenda.Width / 2),
                            (float)(centro.Y + legRaio * Math.Sin(Math.PI * (ânguloAtual + ânguloValor / 2f) / 180) - tamanhoLegenda.Height / 2));

                    } while (legRaio < raio - espaçamento - Math.Max(tamanhoLegenda.Width, tamanhoLegenda.Height)
                        &&
                        tamanhoLegenda.Width >=
                        Distância(centro.X + legRaio * Math.Cos(Math.PI * ânguloAtual / 180) - tamanhoLegenda.Width / 2,
                        centro.X + legRaio * Math.Sin(Math.PI * ânguloAtual / 180) - tamanhoLegenda.Width / 2,
                        centro.X + legRaio * Math.Cos(Math.PI * (ânguloAtual + ânguloValor) / 180) - tamanhoLegenda.Width / 2,
                        centro.X + legRaio * Math.Sin(Math.PI * (ânguloAtual + ânguloValor) / 180) - tamanhoLegenda.Width / 2));

                    if (legRaio < raio - espaçamento - Math.Max(tamanhoLegenda.Width, tamanhoLegenda.Height))
                        g.DrawString(
                            legenda,
                            (Font)props["legendaFont"],
                            (Brush)props["legendaBrush"],
                            posiçãoLegenda);



                    // Escrever descrição (legenda da seqüência)
                    RectangleF regiãoExclusão = new RectangleF(posiçãoLegenda, tamanhoLegenda);

                    legenda = this.legendas[seq];

                    if (legenda.Length > 8 && legenda.IndexOf(' ') > 0)
                    {
                        string[] palavras = legenda.Split(' ');
                        int cnt;

                        legenda = palavras[0];
                        cnt = legenda.Length;

                        for (int i = 1; i < palavras.Length; i++)
                        {
                            cnt += palavras[i].Length;

                            legenda += (cnt > 10 ? '\n' : ' ') + palavras[i];
                        }
                    }

                    tamanhoLegenda = g.MeasureString(
                        legenda,
                        (Font)props["descriçãoFont"]);

                    RectangleF região;

                    do
                    {
                        legRaio += 10;

                        posiçãoLegenda = new PointF(
                            (float)(centro.X + legRaio * Math.Cos(Math.PI * (ânguloAtual + ânguloValor / 2) / 180) - tamanhoLegenda.Width / 2),
                            (float)(centro.Y + legRaio * Math.Sin(Math.PI * (ânguloAtual + ânguloValor / 2) / 180) - tamanhoLegenda.Height / 2));

                        região = new RectangleF(posiçãoLegenda, tamanhoLegenda);
                    } while (legRaio < raio + espaçamento
                        &&
                        regiãoExclusão.IntersectsWith(região));

                    if (legRaio < raio - espaçamento - Math.Max(tamanhoLegenda.Width, tamanhoLegenda.Height))
                        g.DrawString(
                            legenda,
                            (Font)props["descriçãoFont"],
                            (Brush)props["descriçãoBrush"],
                            posiçãoLegenda);

                    g.Flush(System.Drawing.Drawing2D.FlushIntention.Flush);
                    g.Clip = new Region();

                    // Acrescentar ângulo
                    ânguloAtual += ânguloValor;
                }
            }

            return bmp;
        }
コード例 #12
0
ファイル: ItemDrawer.cs プロジェクト: worstward/rlviewer
        private void DrawAlignerAreas(Graphics g, RectangleF screen)
        {
            foreach (var area in _areaAlignerWrapper)
            {
                var areaRect = new RectangleF(area.Area.Location.X, area.Area.Location.Y, area.Area.Width, area.Area.Height);

                if (areaRect.IntersectsWith(screen))
                {
                    using(Pen p = new Pen(Color.Red))
                    {
                        g.DrawRectangle(p, (int)(areaRect.X - screen.X) * Scaler.ScaleFactor,
                           (int)(areaRect.Y - screen.Y) * Scaler.ScaleFactor,
                           areaRect.Width * Scaler.ScaleFactor, areaRect.Height * Scaler.ScaleFactor);
                    }                   
                }
            }
            DrawPoints(g, screen, _areaAlignerWrapper.Where(x => x.SelectedPoint != null).Select(x => x.SelectedPoint.Location));
        }
コード例 #13
0
ファイル: Render.cs プロジェクト: Matt--/travellermap
        public static void RenderTile(RenderContext ctx)
        {
            DateTime dtStart = DateTime.Now;
            List<Timer> timers = new List<Timer>();

            if (ctx.resourceManager == null)
                throw new ArgumentNullException("resourceManager");

            if (ctx.graphics == null)
                throw new ArgumentNullException("graphics");

            if (ctx.selector == null)
                throw new ArgumentNullException("selector");

            XSolidBrush solidBrush = new XSolidBrush();
            XPen pen = new XPen(XColor.Empty);

            using (var fonts = new FontCache(ctx.styles))
            {
                #region resources
                lock (s_imageInitLock)
                {
                    if (ctx.styles.useBackgroundImage && s_backgroundImage == null)
                        s_backgroundImage = XImage.FromFile(ctx.resourceManager.Server.MapPath(@"~/res/Candy/Nebula.png"));

                    if (ctx.styles.showRifts && s_riftImage == null)
                        s_riftImage = new ImageHolder(Image.FromFile(ctx.resourceManager.Server.MapPath(@"~/res/Candy/Rifts.png")));

                    if (ctx.styles.useGalaxyImage && s_galaxyImage == null) {
                        s_galaxyImage = new ImageHolder(Image.FromFile(ctx.resourceManager.Server.MapPath(@"~/res/Candy/Galaxy.png")));
                        s_galaxyImageGray = new ImageHolder(Image.FromFile(ctx.resourceManager.Server.MapPath(@"~/res/Candy/Galaxy_Gray.png")));
                    }

                    if (ctx.styles.useWorldImages && s_worldImages == null)
                    {
                        s_worldImages = new Dictionary<string, XImage> {
                            { "Hyd0", XImage.FromFile(ctx.resourceManager.Server.MapPath(@"~/res/Candy/Hyd0.png")) },
                            { "Hyd1", XImage.FromFile(ctx.resourceManager.Server.MapPath(@"~/res/Candy/Hyd1.png")) },
                            { "Hyd2", XImage.FromFile(ctx.resourceManager.Server.MapPath(@"~/res/Candy/Hyd2.png")) },
                            { "Hyd3", XImage.FromFile(ctx.resourceManager.Server.MapPath(@"~/res/Candy/Hyd3.png")) },
                            { "Hyd4", XImage.FromFile(ctx.resourceManager.Server.MapPath(@"~/res/Candy/Hyd4.png")) },
                            { "Hyd5", XImage.FromFile(ctx.resourceManager.Server.MapPath(@"~/res/Candy/Hyd5.png")) },
                            { "Hyd6", XImage.FromFile(ctx.resourceManager.Server.MapPath(@"~/res/Candy/Hyd6.png")) },
                            { "Hyd7", XImage.FromFile(ctx.resourceManager.Server.MapPath(@"~/res/Candy/Hyd7.png")) },
                            { "Hyd8", XImage.FromFile(ctx.resourceManager.Server.MapPath(@"~/res/Candy/Hyd8.png")) },
                            { "Hyd9", XImage.FromFile(ctx.resourceManager.Server.MapPath(@"~/res/Candy/Hyd9.png")) },
                            { "HydA", XImage.FromFile(ctx.resourceManager.Server.MapPath(@"~/res/Candy/HydA.png")) },
                            { "Belt", XImage.FromFile(ctx.resourceManager.Server.MapPath(@"~/res/Candy/Belt.png")) }
                        };
                    }

                    if (ctx.silly && s_sillyImageColor == null)
                    {
                        // Happy face c/o http://bighappyfaces.com/
                        s_sillyImageColor = XImage.FromFile(ctx.resourceManager.Server.MapPath(@"~/res/AprilFools/Starburst.png"));
                        s_sillyImageGray = XImage.FromFile(ctx.resourceManager.Server.MapPath(@"~/res/AprilFools/Starburst_Gray.png"));
                    }
                }
                #endregion

                timers.Add(new Timer("preload"));
                //////////////////////////////////////////////////////////////
                //
                // Image-Space Rendering
                //
                //////////////////////////////////////////////////////////////

                using (Maps.Rendering.RenderUtil.SaveState(ctx.graphics))
                {
                    if (ctx.clipPath != null)
                    {
                        XMatrix m = ctx.ImageSpaceToWorldSpace;
                        ctx.graphics.MultiplyTransform(m);
                        ctx.graphics.IntersectClip(ctx.clipPath);
                        m.Invert();
                        ctx.graphics.MultiplyTransform(m);
                    }

                    // Fill
                    ctx.graphics.SmoothingMode = XSmoothingMode.HighSpeed;
                    solidBrush.Color = ctx.styles.backgroundColor;
                    ctx.graphics.DrawRectangle(solidBrush, 0, 0, ctx.tileSize.Width, ctx.tileSize.Height);

                    //// Draw tile #
                    //using( var font = new Font( FontFamily.GenericSansSerif, 10 ) )
                    //{
                    //  graphics.DrawString( String.Format( "({0},{1})", x, y ), font, foregroundBrush, 0, 0 );
                    //  graphics.DrawString( String.Format( "{0},{1}-{2}x{3}", tileRect.X, tileRect.Y, tileRect.Width, tileRect.Height ), font, foregroundBrush, 0, 20 );
                    //}

                    // Frame it
                    //graphics.DrawRectangle( Pens.Green, 0, 0, tileSize.Width-1, tileSize.Height-1 );
                }

                timers.Add(new Timer("imagespace"));
                //////////////////////////////////////////////////////////////
                //
                // World-Space Rendering
                //
                //////////////////////////////////////////////////////////////

                // Transform from image-space to world-space. Set up a reverse transform as well.
                XMatrix imageSpaceToWorldSpace = ctx.ImageSpaceToWorldSpace;

                XMatrix worldSpaceToImageSpace = imageSpaceToWorldSpace;
                worldSpaceToImageSpace.Invert();

                ctx.graphics.MultiplyTransform(imageSpaceToWorldSpace);

                using (Maps.Rendering.RenderUtil.SaveState(ctx.graphics))
                {

                    //------------------------------------------------------------
                    // Explicit Clipping
                    //------------------------------------------------------------

                    if (ctx.clipPath != null)
                        ctx.graphics.IntersectClip(ctx.clipPath);

                    //ctx.styles.showPseudoRandomStars = true;
                    //------------------------------------------------------------
                    // Backgrounds
                    //------------------------------------------------------------

                    RectangleF galacticBounds = new RectangleF(-14598.67f, -23084.26f, 29234.1133f, 25662.4746f); // TODO: Don't hardcode
                    Rectangle galaxyImageRect = new Rectangle(-18257, -26234, 36551, 32462); // Chosen to match T5 pp.416

                    // This transforms the Linehan galactic structure to the Mikesh galactic structure
                    // See http://travellermap.blogspot.com/2009/03/galaxy-scale-mismatch.html
                    Matrix xformLinehanToMikesh = new Matrix(0.9181034f, 0.0f, 0.0f, 0.855192542f, 120.672432f, 86.34569f);
                    timers.Add(new Timer("prep"));

                    //------------------------------------------------------------
                    // Local background (Nebula)
                    //------------------------------------------------------------
                    #region nebula-background

                    // NOTE: Since alpha texture brushes aren't supported without
                    // creating a new image (slow!) we render the local background
                    // first, then overlay the deep background over it, for
                    // basically the same effect since the alphas sum to 1.

                    if (ctx.styles.useBackgroundImage && galacticBounds.IntersectsWith(ctx.tileRect))
                    {
                        // Image-space rendering, so save current context
                        using (RenderUtil.SaveState(ctx.graphics))
                        {
                            // Never fill outside the galaxy
                            ctx.graphics.IntersectClip(galacticBounds);

                            // Map back to image space so it scales/tiles nicely
                            ctx.graphics.MultiplyTransform(worldSpaceToImageSpace);

                            const float backgroundImageScale = 2.0f;

                            lock (s_backgroundImage)
                            {
                                // Scaled size of the background
                                double w = s_backgroundImage.PixelWidth * backgroundImageScale;
                                double h = s_backgroundImage.PixelHeight * backgroundImageScale;

                                // Offset of the background, relative to the canvas
                                double ox = (float)(-ctx.tileRect.Left * ctx.scale * Astrometrics.ParsecScaleX) % w;
                                double oy = (float)(-ctx.tileRect.Top * ctx.scale * Astrometrics.ParsecScaleY) % h;
                                if (ox > 0) ox -= w;
                                if (oy > 0) oy -= h;

                                // Number of copies needed to cover the canvas
                                int nx = 1 + (int)Math.Floor(ctx.tileSize.Width / w);
                                int ny = 1 + (int)Math.Floor(ctx.tileSize.Height / h);
                                if (ox + nx * w < ctx.tileSize.Width) nx += 1;
                                if (oy + ny * h < ctx.tileSize.Height) ny += 1;

                                for (int x = 0; x < nx; ++x)
                                {
                                    for (int y = 0; y < ny; ++y)
                                    {
                                        ctx.graphics.DrawImage(s_backgroundImage, ox + x * w, oy + y * h, w + 1, h + 1);
                                        //ctx.graphics.DrawRectangle( XPens.Orange, ox + x * w, oy + y * h, w, h );
                                    }
                                }
                            }
                        }
                    }
                    #endregion
                    timers.Add(new Timer("background (nebula)"));

                    //------------------------------------------------------------
                    // Deep background (Galaxy)
                    //------------------------------------------------------------
                    #region galaxy-background
                    if (ctx.styles.useGalaxyImage && ctx.styles.deepBackgroundOpacity > 0f)
                    {
                        using (RenderUtil.SaveState(ctx.graphics))
                        {
                            ctx.graphics.MultiplyTransform(xformLinehanToMikesh);
                            ImageHolder galaxyImage = ctx.styles.lightBackground ? s_galaxyImageGray : s_galaxyImage;
                            lock (galaxyImage)
                            {
                                RenderUtil.DrawImageAlpha(ctx.graphics, ctx.styles.deepBackgroundOpacity, galaxyImage, galaxyImageRect);
                            }
                        }
                    }
                    #endregion
                    timers.Add(new Timer("background (galaxy)"));

                    //------------------------------------------------------------
                    // Pseudo-Random Stars
                    //------------------------------------------------------------
                    #region pseudorandom-stars

                    if (ctx.styles.pseudoRandomStars.visible)
                    {
                        // Render pseudorandom stars based on the tile # and
                        // scale factor. Note that these are positioned in
                        // screen space, not world space.

                        //const int nStars = 75;
                        int nMinStars = ctx.tileSize.Width * ctx.tileSize.Height / 300;
                        int nStars = ctx.scale >= 1 ? nMinStars : (int)(nMinStars / ctx.scale);

                        // NOTE: For performance's sake, three different cases are considered:
                        // (1) Tile is entirely within charted space (most common) - just render
                        //     the pseudorandom stars into the tile
                        // (2) Tile intersects the galaxy bounds - render pseudorandom stars
                        //     into a texture, then fill the galaxy vector with it
                        // (3) Tile is entire outside the galaxy - don't render stars

                        using (RenderUtil.SaveState(ctx.graphics))
                        {
                            ctx.graphics.SmoothingMode = XSmoothingMode.HighQuality;
                            solidBrush.Color = ctx.styles.pseudoRandomStars.fillColor;

                            Random rand = new Random((((int)ctx.tileRect.Left) << 8) ^ (int)ctx.tileRect.Top);
                            for (int i = 0; i < nStars; i++)
                            {
                                float starX = (float)rand.NextDouble() * ctx.tileRect.Width + ctx.tileRect.X;
                                float starY = (float)rand.NextDouble() * ctx.tileRect.Height + ctx.tileRect.Y;
                                float d = (float)rand.NextDouble() * 2;

                                //ctx.graphics.DrawRectangle( fonts.foregroundBrush, starX, starY, (float)( d / ctx.scale * Astrometrics.ParsecScaleX ), (float)( d / ctx.scale * Astrometrics.ParsecScaleY ) );
                                ctx.graphics.DrawEllipse(solidBrush, starX, starY, (float)(d / ctx.scale * Astrometrics.ParsecScaleX), (float)(d / ctx.scale * Astrometrics.ParsecScaleY));
                            }
                        }
                    }
                    #endregion
                    timers.Add(new Timer("pseudorandom"));

                    //------------------------------------------------------------
                    // Rifts in Charted Space
                    //------------------------------------------------------------
                    #region rifts

                    if (ctx.styles.showRifts && ctx.styles.riftOpacity > 0f)
                    {
                        Rectangle riftImageRect;
                        riftImageRect = new Rectangle(-1374, -827, 2769, 1754); // Correct
                        lock (s_riftImage)
                        {
                            RenderUtil.DrawImageAlpha(ctx.graphics, ctx.styles.riftOpacity, s_riftImage, riftImageRect);
                        }
                    }
                    #endregion
                    timers.Add(new Timer("rifts"));

                    //------------------------------------------------------------
                    // April Fool's Day
                    //------------------------------------------------------------
                    #region april-fools

                    if (ctx.silly)
                    {
                        using (RenderUtil.SaveState(ctx.graphics))
                        {
                            // Render in image-space
                            ctx.graphics.MultiplyTransform(worldSpaceToImageSpace);

                            XImage sillyImage = ctx.styles.grayscale ? s_sillyImageGray : s_sillyImageColor;

                            lock (sillyImage)
                            {
                                ctx.graphics.DrawImage(sillyImage, 0, 0, ctx.tileSize.Width, ctx.tileSize.Height);
                            }
                        }
                        timers.Add(new Timer("silly"));
                    }

                    #endregion

                    //------------------------------------------------------------
                    // Macro: Borders object
                    //------------------------------------------------------------
                    #region macro-borders
                    if (ctx.styles.macroBorders.visible)
                    {
                        ctx.styles.macroBorders.pen.Apply(ref pen);
                        ctx.graphics.SmoothingMode = XSmoothingMode.AntiAlias;
                        foreach (var vec in borderFiles
                            .Select(file => ctx.resourceManager.GetXmlFileObject(file, typeof(VectorObject)))
                            .OfType<VectorObject>()
                            .Where(vec => (vec.MapOptions & ctx.options & MapOptions.BordersMask) != 0))
                        {
                            vec.Draw(ctx.graphics, ctx.tileRect, ctx.options, pen);
                        }

                    }
                    #endregion
                    timers.Add(new Timer("macro-borders"));

                    //------------------------------------------------------------
                    // Macro: Route object
                    //------------------------------------------------------------
                    #region macro-routes

                    if (ctx.styles.macroRoutes.visible)
                    {
                        ctx.styles.macroRoutes.pen.Apply(ref pen);
                        ctx.graphics.SmoothingMode = XSmoothingMode.AntiAlias;
                        foreach (var vec in routeFiles
                            .Select(file => ctx.resourceManager.GetXmlFileObject(file, typeof(VectorObject)))
                            .OfType<VectorObject>()
                            .Where(vec => (vec.MapOptions & ctx.options & MapOptions.BordersMask) != 0))
                        {
                            vec.Draw(ctx.graphics, ctx.tileRect, ctx.options, pen);
                        }
                    }
                    #endregion
                    timers.Add(new Timer("macro-routes"));

                    //------------------------------------------------------------
                    // Sector Grid
                    //------------------------------------------------------------
                    #region sector-grid

                    ctx.graphics.SmoothingMode = XSmoothingMode.HighSpeed;

                    if (ctx.styles.sectorGrid.visible)
                    {
                        const int gridSlop = 10;
                        ctx.styles.sectorGrid.pen.Apply(ref pen);

                        for (float h = ((float)(Math.Floor((ctx.tileRect.Left) / Astrometrics.SectorWidth) - 1) - Astrometrics.ReferenceSector.X) * Astrometrics.SectorWidth - Astrometrics.ReferenceHex.X; h <= ctx.tileRect.Right + Astrometrics.SectorWidth; h += Astrometrics.SectorWidth)
                            ctx.graphics.DrawLine(pen, h, ctx.tileRect.Top - gridSlop, h, ctx.tileRect.Bottom + gridSlop);

                        for (float v = ((float)(Math.Floor((ctx.tileRect.Top) / Astrometrics.SectorHeight) - 1) - Astrometrics.ReferenceSector.Y) * Astrometrics.SectorHeight - Astrometrics.ReferenceHex.Y; v <= ctx.tileRect.Bottom + Astrometrics.SectorHeight; v += Astrometrics.SectorHeight)
                            ctx.graphics.DrawLine(pen, ctx.tileRect.Left - gridSlop, v, ctx.tileRect.Right + gridSlop, v);
                    }

                    #endregion
                    timers.Add(new Timer("sector grid"));

                    //------------------------------------------------------------
                    // Subsector Grid
                    //------------------------------------------------------------
                    #region subsector-grid
                    ctx.graphics.SmoothingMode = XSmoothingMode.HighSpeed;
                    if (ctx.styles.subsectorGrid.visible)
                    {
                        const int gridSlop = 10;
                        ctx.styles.subsectorGrid.pen.Apply(ref pen);

                        int hmin = (int)Math.Floor(ctx.tileRect.Left / Astrometrics.SubsectorWidth) - 1 - Astrometrics.ReferenceSector.X,
                            hmax = (int)Math.Ceiling((ctx.tileRect.Right + Astrometrics.SubsectorWidth + Astrometrics.ReferenceHex.X) / Astrometrics.SubsectorWidth);
                        for (int hi = hmin; hi <= hmax; ++hi)
                        {
                            if (hi % 4 == 0) continue;
                            float h = hi * Astrometrics.SubsectorWidth - Astrometrics.ReferenceHex.X;
                            ctx.graphics.DrawLine(pen, h, ctx.tileRect.Top - gridSlop, h, ctx.tileRect.Bottom + gridSlop);
                        }

                        int vmin = (int)Math.Floor(ctx.tileRect.Top / Astrometrics.SubsectorHeight) - 1 - Astrometrics.ReferenceSector.Y,
                            vmax = (int)Math.Ceiling((ctx.tileRect.Bottom + Astrometrics.SubsectorHeight + Astrometrics.ReferenceHex.Y) / Astrometrics.SubsectorHeight);
                        for (int vi = vmin; vi <= vmax; ++vi)
                        {
                            if (vi % 4 == 0) continue;
                            float v = vi * Astrometrics.SubsectorHeight - Astrometrics.ReferenceHex.Y;
                            ctx.graphics.DrawLine(pen, ctx.tileRect.Left - gridSlop, v, ctx.tileRect.Right + gridSlop, v);
                        }
                    }
                    #endregion
                    timers.Add(new Timer("subsector grid"));

                    //------------------------------------------------------------
                    // Parsec Grid
                    //------------------------------------------------------------
                    #region parsec-grid
                    // TODO: Optimize - timers indicate this is slow
                    ctx.graphics.SmoothingMode = XSmoothingMode.HighQuality;
                    if (ctx.styles.parsecGrid.visible)
                    {
                        const int parsecSlop = 1;

                        int hx = (int)Math.Floor(ctx.tileRect.Left);
                        int hw = (int)Math.Ceiling(ctx.tileRect.Width);
                        int hy = (int)Math.Floor(ctx.tileRect.Top);
                        int hh = (int)Math.Ceiling(ctx.tileRect.Height);

                        ctx.styles.parsecGrid.pen.Apply(ref pen);

                        switch (ctx.styles.hexStyle)
                        {
                            case HexStyle.Square:
                                for (int px = hx - parsecSlop; px < hx + hw + parsecSlop; px++)
                                {
                                    float yOffset = ((px % 2) != 0) ? 0.0f : 0.5f;
                                    for (int py = hy - parsecSlop; py < hy + hh + parsecSlop; py++)
                                    {
                                        // TODO: use RenderUtil.(Square|Hex)Edges(X|Y) arrays
                                        const float inset = 0.1f;
                                        ctx.graphics.DrawRectangle(pen, px + inset, py + inset + yOffset, 1 - inset * 2, 1 - inset * 2);
                                    }
                                }
                                break;

                            case HexStyle.Hex:
                                XPoint[] points = new XPoint[4];
                                for (int px = hx - parsecSlop; px < hx + hw + parsecSlop; px++)
                                {
                                    double yOffset = ((px % 2) != 0) ? 0.0 : 0.5;
                                    for (int py = hy - parsecSlop; py < hy + hh + parsecSlop; py++)
                                    {
                                        points[0] = new XPoint(px + -RenderUtil.HEX_EDGE, py + 0.5 + yOffset);
                                        points[1] = new XPoint(px + RenderUtil.HEX_EDGE, py + 1.0 + yOffset);
                                        points[2] = new XPoint(px + 1.0 - RenderUtil.HEX_EDGE, py + 1.0 + yOffset);
                                        points[3] = new XPoint(px + 1.0 + RenderUtil.HEX_EDGE, py + 0.5 + yOffset);
                                        ctx.graphics.DrawLines(pen, points);
                                    }
                                }
                                break;
                            case HexStyle.None:
                                // none
                                break;
                        }

                        if (ctx.styles.numberAllHexes &&
                            ctx.styles.worldDetails.HasFlag(WorldDetails.Hex))
                        {
                            solidBrush.Color = ctx.styles.hexNumber.textColor;
                            for (int px = hx - parsecSlop; px < hx + hw + parsecSlop; px++)
                            {
                                double yOffset = ((px % 2) != 0) ? 0.0 : 0.5;
                                for (int py = hy - parsecSlop; py < hy + hh + parsecSlop; py++)
                                {
                                    Location loc = Astrometrics.CoordinatesToLocation(px + 1, py + 1);
                                    string hex;
                                    switch (ctx.styles.hexCoordinateStyle)
                                    {
                                        default:
                                        case Stylesheet.HexCoordinateStyle.Sector: hex = loc.HexString; break;
                                        case Stylesheet.HexCoordinateStyle.Subsector: hex = loc.SubsectorHexString; break;
                                    }
                                    using (RenderUtil.SaveState(ctx.graphics))
                                    {
                                        XMatrix matrix = new XMatrix();
                                        matrix.TranslatePrepend(px + 0.5f, py + yOffset);
                                        matrix.ScalePrepend(ctx.styles.hexContentScale / Astrometrics.ParsecScaleX, ctx.styles.hexContentScale / Astrometrics.ParsecScaleY);
                                        ctx.graphics.MultiplyTransform(matrix, XMatrixOrder.Prepend);
                                        ctx.graphics.DrawString(hex, ctx.styles.hexNumber.Font, solidBrush, 0, 0, RenderUtil.StringFormatTopCenter);
                                    }
                                }
                            }
                        }
                    }
                    #endregion
                    timers.Add(new Timer("parsec grid"));

                    //------------------------------------------------------------
                    // Subsector Names
                    //------------------------------------------------------------
                    #region subsector-names

                    if (ctx.styles.subsectorNames.visible)
                    {
                        solidBrush.Color = ctx.styles.subsectorNames.textColor;
                        foreach (Sector sector in ctx.selector.Sectors)
                        {
                            for (int i = 0; i < 16; i++)
                            {
                                int ssx = i % 4;
                                int ssy = i / 4;

                                Subsector ss = sector[i];
                                if (ss == null || String.IsNullOrEmpty(ss.Name))
                                    continue;

                                Point center = sector.SubsectorCenter(i);
                                RenderUtil.DrawLabel(ctx.graphics, ss.Name, center, ctx.styles.subsectorNames.Font, solidBrush, ctx.styles.subsectorNames.textStyle);
                            }
                        }
                    }

                    #endregion
                    timers.Add(new Timer("subsector names"));

                    //------------------------------------------------------------
                    // Micro: Borders
                    //------------------------------------------------------------
                    #region micro-borders
                    if (ctx.styles.microBorders.visible)
                    {
                        if (ctx.styles.fillMicroBorders)
                            DrawMicroBorders(ctx, BorderLayer.Fill);
                        DrawMicroBorders(ctx, BorderLayer.Stroke);
                    }
                    #endregion
                    timers.Add(new Timer("micro-borders"));

                    //------------------------------------------------------------
                    // Micro: Routes
                    //------------------------------------------------------------
                    #region micro-routes

                    if (ctx.styles.microRoutes.visible)
                        DrawRoutes(ctx, fonts);

                    #endregion
                    timers.Add(new Timer("micro-routes"));

                    //------------------------------------------------------------
                    // Sector Names
                    //------------------------------------------------------------
                    #region sector-names

                    if (ctx.styles.showSomeSectorNames || ctx.styles.showAllSectorNames)
                    {
                        foreach (Sector sector in ctx.selector.Sectors
                            .Where(sector => ctx.styles.showAllSectorNames || (ctx.styles.showSomeSectorNames && sector.Selected))
                            .Where(sector => sector.Names.Any() || sector.Label != null))
                        {
                            solidBrush.Color = ctx.styles.sectorName.textColor;
                            string name = sector.Label ?? sector.Names[0].Text;

                            RenderUtil.DrawLabel(ctx.graphics, name, sector.Center, ctx.styles.sectorName.Font, solidBrush, ctx.styles.sectorName.textStyle);
                        }
                    }

                    #endregion
                    timers.Add(new Timer("sector names"));

                    //------------------------------------------------------------
                    // Mega: Galaxy-Scale Labels
                    //------------------------------------------------------------
                    #region mega-names
                    if (ctx.styles.megaNames.visible)
                    {
                        solidBrush.Color = ctx.styles.megaNames.textColor;
                        foreach (var label in megaLabels)
                        {
                            using (RenderUtil.SaveState(ctx.graphics))
                            {
                                XMatrix matrix = new XMatrix();
                                matrix.ScalePrepend(1.0f / Astrometrics.ParsecScaleX, 1.0f / Astrometrics.ParsecScaleY);
                                matrix.TranslatePrepend(label.position.X, label.position.Y);
                                ctx.graphics.MultiplyTransform(matrix, XMatrixOrder.Prepend);

                                XFont font = label.minor ? ctx.styles.megaNames.SmallFont : ctx.styles.megaNames.Font;
                                XSize size = ctx.graphics.MeasureString(label.text, font);
                                ctx.graphics.TranslateTransform(-size.Width / 2, -size.Height / 2); // Center the text
                                RectangleF textBounds = new RectangleF(0, 0, (float)size.Width * 1.01f, (float)size.Height * 2); // *2 or it gets cut off at high sizes
                                XTextFormatter formatter = new XTextFormatter(ctx.graphics);
                                formatter.Alignment = XParagraphAlignment.Center;
                                formatter.DrawString(label.text, font, solidBrush, textBounds);
                            }
                        }
                    }
                    #endregion
                    timers.Add(new Timer("mega names"));

                    //------------------------------------------------------------
                    // Macro: Government / Rift / Route Names
                    //------------------------------------------------------------
                    #region government-rift-names
                    if (ctx.styles.macroNames.visible)
                    {
                        foreach (var vec in borderFiles
                            .Select(file => ctx.resourceManager.GetXmlFileObject(file, typeof(VectorObject)))
                            .OfType<VectorObject>()
                            .Where(vec => (vec.MapOptions & ctx.options & MapOptions.NamesMask) != 0))
                        {
                            bool major = vec.MapOptions.HasFlag(MapOptions.NamesMajor);
                            LabelStyle labelStyle = new LabelStyle();
                            labelStyle.Uppercase = major;
                            XFont font = major ? ctx.styles.macroNames.Font : ctx.styles.macroNames.SmallFont;
                            solidBrush.Color = major ? ctx.styles.macroNames.textColor : ctx.styles.macroNames.textHighlightColor;
                            vec.DrawName(ctx.graphics, ctx.tileRect, ctx.options, font, solidBrush, labelStyle);
                        }

                        foreach (var vec in riftFiles
                            .Select(file => ctx.resourceManager.GetXmlFileObject(file, typeof(VectorObject)))
                            .OfType<VectorObject>()
                            .Where(vec => (vec.MapOptions & ctx.options & MapOptions.NamesMask) != 0))
                        {
                            bool major = vec.MapOptions.HasFlag(MapOptions.NamesMajor);
                            LabelStyle labelStyle = new LabelStyle();
                            labelStyle.Rotation = 35;
                            labelStyle.Uppercase = major;
                            XFont font = major ? ctx.styles.macroNames.Font : ctx.styles.macroNames.SmallFont;
                            solidBrush.Color = major ? ctx.styles.macroNames.textColor : ctx.styles.macroNames.textHighlightColor;
                            vec.DrawName(ctx.graphics, ctx.tileRect, ctx.options, font, solidBrush, labelStyle);
                        }

                        if (ctx.styles.macroRoutes.visible)
                        {
                            foreach (var vec in routeFiles
                                .Select(file => ctx.resourceManager.GetXmlFileObject(file, typeof(VectorObject)))
                                .OfType<VectorObject>()
                                .Where(vec => (vec.MapOptions & ctx.options & MapOptions.NamesMask) != 0))
                            {
                                bool major = vec.MapOptions.HasFlag(MapOptions.NamesMajor);
                                LabelStyle labelStyle = new LabelStyle();
                                labelStyle.Uppercase = major;
                                XFont font = major ? ctx.styles.macroNames.Font : ctx.styles.macroNames.SmallFont;
                                solidBrush.Color = major ? ctx.styles.macroRoutes.textColor : ctx.styles.macroRoutes.textHighlightColor;
                                vec.DrawName(ctx.graphics, ctx.tileRect, ctx.options, font, solidBrush, labelStyle);
                            }
                        }

                        if (ctx.options.HasFlag(MapOptions.NamesMinor))
                        {
                            XFont font = ctx.styles.macroNames.MediumFont;
                            solidBrush.Color = ctx.styles.macroRoutes.textHighlightColor;
                            foreach (var label in labels)
                            {
                                using (RenderUtil.SaveState(ctx.graphics))
                                {
                                    XMatrix matrix = new XMatrix();
                                    matrix.ScalePrepend(1.0f / Astrometrics.ParsecScaleX, 1.0f / Astrometrics.ParsecScaleY);
                                    matrix.TranslatePrepend(label.position.X, label.position.Y);
                                    ctx.graphics.MultiplyTransform(matrix, XMatrixOrder.Prepend);

                                    XSize size = ctx.graphics.MeasureString(label.text, font);
                                    ctx.graphics.TranslateTransform(-size.Width / 2, -size.Height / 2); // Center the text
                                    RectangleF textBounds = new RectangleF(0, 0, (float)size.Width, (float)size.Height * 2); // *2 or it gets cut off at high sizes
                                    XTextFormatter formatter = new XTextFormatter(ctx.graphics);
                                    formatter.Alignment = XParagraphAlignment.Center;
                                    formatter.DrawString(label.text, font, solidBrush, textBounds);
                                }
                            }

                        }
                    }

                    #endregion
                    timers.Add(new Timer("macro names"));

                    //------------------------------------------------------------
                    // Macro: Capitals & Home Worlds
                    //------------------------------------------------------------
                    #region capitals-homeworlds

                    if (ctx.styles.capitals.visible && (ctx.options & MapOptions.WorldsMask) != 0)
                    {
                        WorldObjectCollection worlds = ctx.resourceManager.GetXmlFileObject(@"~/res/Worlds.xml", typeof(WorldObjectCollection)) as WorldObjectCollection;
                        if (worlds != null)
                        {
                            solidBrush.Color = ctx.styles.capitals.textColor;
                            foreach (WorldObject world in worlds.Worlds.Where(world => (world.MapOptions & ctx.options) != 0))
                            {
                                world.Paint(ctx.graphics, ctx.tileRect, ctx.options, ctx.styles.capitals.fillColor,
                                    solidBrush, ctx.styles.macroNames.SmallFont);
                            }
                        }
                    }

                    #endregion
                    timers.Add(new Timer("macro worlds"));

                    //------------------------------------------------------------
                    // Micro: Border Labels & Explicit Labels
                    //------------------------------------------------------------
                    #region micro-border-labels

                    if (ctx.styles.showMicroNames)
                        DrawLabels(ctx, fonts);

                    #endregion
                    timers.Add(new Timer("micro-border labels"));
                }

                // End of clipping, so world names are not clipped in jumpmaps.

                //------------------------------------------------------------
                // Worlds
                //------------------------------------------------------------
                #region worlds
                if (ctx.styles.worlds.visible)
                {
                    // TODO: selector may be expensive
                    foreach (World world in ctx.selector.Worlds) { DrawWorld(ctx, fonts, world, WorldLayer.Background); }
                    foreach (World world in ctx.selector.Worlds) { DrawWorld(ctx, fonts, world, WorldLayer.Foreground); }
                }
                #endregion
                timers.Add(new Timer("worlds"));

                //------------------------------------------------------------
                // Unofficial
                //------------------------------------------------------------
                #region unofficial

                if (ctx.styles.dimUnofficialSectors && ctx.styles.worlds.visible)
                {
                    solidBrush.Color = Color.FromArgb(128, ctx.styles.backgroundColor);
                    foreach (Sector sector in ctx.selector.Sectors
                        .Where(sector => !sector.Tags.Contains("Official") && !sector.Tags.Contains("Preserve") && !sector.Tags.Contains("InReview")))
                        ctx.graphics.DrawRectangle(solidBrush, sector.Bounds);
                }

                #endregion

            #if SHOW_TIMING
                using( RenderUtil.SaveState( ctx.graphics ) )
                {
                    XFont font = new XFont( FontFamily.GenericSansSerif, 12, XFontStyle.Regular, new XPdfFontOptions(PdfSharp.Pdf.PdfFontEncoding.Unicode) );
                    ctx.graphics.MultiplyTransform( worldSpaceToImageSpace );
                    double cursorX = 20.0, cursorY = 20.0;
                    DateTime last = dtStart;
                    foreach( Timer s in timers )
                    {
                        TimeSpan ts = s.dt - last;
                        last = s.dt;
                        for( int dx = -1; dx <= 1; ++dx )
                        {
                            for( int dy = -1; dy <= 1; ++dy )
                            {

                                ctx.graphics.DrawString( String.Format( "{0} {1}", Math.Round( ts.TotalMilliseconds ), s.label ), font, XBrushes.Black, cursorX + dx, cursorY + dy );
                            }
                        }
                        ctx.graphics.DrawString( String.Format("{0} {1}", Math.Round(ts.TotalMilliseconds), s.label), font, XBrushes.Yellow, cursorX, cursorY );
                        cursorY += 14;
                    }
                }
            #endif

            }
        }
コード例 #14
0
ファイル: AddAScout.cs プロジェクト: bobreck/Pack957
        protected virtual void KeyboardWillShowNotification(NSNotification notification)
        {
            UIView activeView = KeyboardGetActiveView();
            if (activeView == null)
                return;

            UIScrollView scrollView = activeView.FindSuperviewOfType(this.View, typeof(UIScrollView)) as UIScrollView;
            if (scrollView == null)
                return;

            RectangleF keyboardBounds = UIKeyboard.FrameBeginFromNotification(notification);

            UIEdgeInsets contentInsets = new UIEdgeInsets(0.0f, 0.0f, keyboardBounds.Size.Height, 0.0f);
            scrollView.ContentInset = contentInsets;
            scrollView.ScrollIndicatorInsets = contentInsets;

            // If activeField is hidden by keyboard, scroll it so it's visible
            RectangleF viewRectAboveKeyboard = new RectangleF(this.View.Frame.Location, new SizeF(this.View.Frame.Width, this.View.Frame.Size.Height - keyboardBounds.Size.Height));

            RectangleF activeFieldAbsoluteFrame = activeView.Superview.ConvertRectToView(activeView.Frame, this.View);
            // activeFieldAbsoluteFrame is relative to this.View so does not include any scrollView.ContentOffset

            // Check if the activeField will be partially or entirely covered by the keyboard
            PointF scrollPoint = new PointF (0.0f, activeFieldAbsoluteFrame.Location.Y + activeFieldAbsoluteFrame.Height + scrollView.ContentOffset.Y - viewRectAboveKeyboard.Height);
            // Check if the activeField will be partially or entirely covered by the keyboard
            if (viewRectAboveKeyboard.IntersectsWith (activeFieldAbsoluteFrame) &&
                ! viewRectAboveKeyboard.Contains (activeFieldAbsoluteFrame)) {
                scrollView.SetContentOffset (scrollPoint, true);
            } else if (!viewRectAboveKeyboard.Contains (activeFieldAbsoluteFrame)) {
                scrollView.SetContentOffset (scrollPoint, true);
            }
        }
コード例 #15
0
ファイル: D2dTimelineRenderer.cs プロジェクト: boshlong/ATF
 /// <summary>
 /// Finds hits on a marker, given a picking rectangle</summary>
 /// <param name="marker">Marker</param>
 /// <param name="bounds">Bounding rectangle, computed during layout phase</param>
 /// <param name="pickRect">Picking rectangle</param>
 /// <param name="c">Drawing context</param>
 /// <returns>Type of hit</returns>
 protected virtual HitType Pick(IMarker marker, RectangleF bounds, RectangleF pickRect, Context c)
 {
     return bounds.IntersectsWith(pickRect) ? HitType.Marker : HitType.None;
 }
コード例 #16
0
        void Scrolled(object sender, EventArgs args)
        {
            if (UICardPlace.Decelerating)
                GetCenteredBlock ();

            var proposedContentOffset = UICardPlace.ContentOffset;
            float horizontalCenter = (float)(proposedContentOffset.X + (UICardPlace.Bounds.Size.Width / 2.0));

            RectangleF pointer = new RectangleF (horizontalCenter, 10, 10, 10);
            var matched = _words.FirstOrDefault(x=>pointer.IntersectsWith (x.Frame));
            if (matched!=null) {
                switch (matched.Status) {
                case 3:
                    View.BackgroundColor = UIColor.Red;
                    break;
                case 1:
                    View.BackgroundColor = UIColor.Green;
                    break;
                case 2:
                    View.BackgroundColor = UIColor.Yellow;
                    break;
                default:
                    View.BackgroundColor = UIColor.Gray;
                    break;
                }
            }
        }
        public override void Draw(GraphicsWrapper g, PointF? mousePosition, RectangleF clippingRectangle, RectangleF drawingSpace)
        {
            if (Visible == false)
            {
                return;
            }

            if (_controlPoints.Count < 1)
            {
                return;
            }

            PointF point1 = _controlPoints[0];
            PointF point2;
            if (_controlPoints.Count < 2)
            {
                point2 = mousePosition.Value;
            }
            else
            {
                point2 = _controlPoints[1];
            }

            // Clipping opitmization.
            RectangleF rectangle = new RectangleF(
                Math.Min(point1.X, point2.X), Math.Min(point1.Y, point2.Y),
                Math.Abs(point2.X - point1.X), Math.Abs(point2.Y - point1.Y));

            if (rectangle.IntersectsWith(clippingRectangle) == false)
            {
                return;
            }

            // Draw base line.
            g.DrawLine(_dashedLinePen, point1, point2);

            float baseLevel = point1.Y;
            float height = point2.Y - point1.Y;

            // Draw fibbonacci levels.
            float[] levels = new float[] { 0, 23.6f, 38.2f, 50, 61.8f, 100 };
            for (int i = 0; i < levels.Length; i++)
            {
                float actualLevel = baseLevel + height * levels[i] / 100f;
                g.DrawLine(_solidLinePen, point1.X, actualLevel, point2.X, actualLevel);
                g.DrawString(levels[i].ToString(), DefaultDynamicObjectFont, Brushes.White, point1.X, actualLevel);
            }

            if (Selected)
            {
                DrawControlPoints(g);
            }
        }
コード例 #18
0
ファイル: DepthBar.cs プロジェクト: skcajs/Tomb-Editor-Public
        public void Draw(PaintEventArgs e, Size parentControlSize, Vector2 cursorPos, Func <Room, Brush, ConditionallyOwned <Brush> > getRoomBrush)
        {
            RectangleF barArea            = getBarArea(parentControlSize);
            float      selectedLimit0PosY = ToVisualY(barArea, _selectedLimit0);
            float      selectedLimit1PosY = ToVisualY(barArea, _selectedLimit1);

            // Draw box
            e.Graphics.FillRectangle(_backgroundBrush, barArea);

            // Draw height lines
            if (barArea.IntersectsWith(e.ClipRectangle))
            {
                e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
                for (int depth = (int)MinDepth; depth <= (int)MaxDepth; ++depth)
                {
                    float posY = ToVisualY(barArea, depth);
                    e.Graphics.DrawLine(_heightLinesPen, barArea.Left, posY, barArea.Right, posY);
                }
                e.Graphics.SmoothingMode = SmoothingMode.Default;
            }

            // Draw height strings
            for (int i = 0; i <= _heightStringCount; ++i)
            {
                float depth = MaxDepth - (MaxDepth - MinDepth) / _heightStringCount * i;
                float posY  = ToVisualY(barArea, depth);

                // Hide height string when close to selection limits
                float distanceToSelectionLimit0 = Math.Abs(posY - selectedLimit0PosY);
                float distanceToSelectionLimit1 = Math.Abs(posY - selectedLimit1PosY);
                float distance = Math.Min(distanceToSelectionLimit0, distanceToSelectionLimit1) - _heightStringFont.Height * 0.85f;

                if (distance > _heightStringFadeDistance)
                {
                    DrawHeightString(e, barArea, _outlinePen, (float)Math.Round(depth));

                    if (i > 0 && i < _heightStringCount)
                    {
                        e.Graphics.DrawLine(_heightLinesBigPen, barArea.Left, posY, barArea.Right, posY);
                    }
                }
                else if (distance > 0.0f)
                {
                    using (var alphaOutlinePen = (Pen)_outlinePen.Clone())
                    {
                        alphaOutlinePen.Color = Color.FromArgb((int)(alphaOutlinePen.Color.A * (distance / _heightStringFadeDistance)),
                                                               alphaOutlinePen.Color.R, alphaOutlinePen.Color.G, alphaOutlinePen.Color.B);
                        DrawHeightString(e, barArea, alphaOutlinePen, (float)Math.Round(depth));
                    }
                    if (i > 0 && i < _heightStringCount)
                    {
                        using (var alphaPen = (Pen)_heightLinesBigPen.Clone())
                        {
                            alphaPen.Color = Color.FromArgb((int)(alphaPen.Color.A * (distance / _heightStringFadeDistance)),
                                                            alphaPen.Color.R, alphaPen.Color.G, alphaPen.Color.B);
                            e.Graphics.DrawLine(alphaPen, barArea.Left, posY, barArea.Right, posY);
                        }
                    }
                }
            }

            // Draw common selection range
            DrawHeightString(e, barArea, _selectionPen, _selectedLimit0, true);
            DrawHeightString(e, barArea, _selectionPen, _selectedLimit1, true);

            RectangleF selectionRect = new RectangleF(new PointF(barArea.Left, Math.Min(selectedLimit1PosY, selectedLimit0PosY)),
                                                      new SizeF(_barWidth, Math.Abs(selectedLimit0PosY - selectedLimit1PosY)));

            e.Graphics.FillRectangle(_selectionBrush, selectionRect);

            // Draw probe selection ranges
            if (!barArea.Contains(e.ClipRectangle))
            {
                for (int groupIndex = 0; groupIndex < DepthProbes.Count; ++groupIndex)
                {
                    RectangleF groupArea = groupGetArea(barArea, groupIndex);
                    selectionRect = new RectangleF(new PointF(groupArea.Left, Math.Min(selectedLimit1PosY, selectedLimit0PosY)),
                                                   new SizeF(groupArea.Width, Math.Abs(selectedLimit0PosY - selectedLimit1PosY)));

                    using (var b = new SolidBrush(Color.FromArgb(60, DepthProbes[groupIndex].Color.R, DepthProbes[groupIndex].Color.G, DepthProbes[groupIndex].Color.B)))
                        e.Graphics.FillRectangle(b, selectionRect);
                }
            }

            // Draw depth bar content
            if (barArea.IntersectsWith(e.ClipRectangle))
            {
                // Draw group
                for (int groupIndex = 0; groupIndex < GroupCount; ++groupIndex)
                {
                    RectangleF groupArea = groupGetArea(barArea, groupIndex);
                    if (!groupArea.IntersectsWith(e.ClipRectangle))
                    {
                        continue;
                    }

                    // Draw sequences
                    List <List <RelevantRoom> > roomSequences = groupBuildRoomSequences(cursorPos, groupIndex);
                    float sequenceWidth = groupArea.Width / roomSequences.Count;
                    for (int roomSequenceIndex = 0; roomSequenceIndex < roomSequences.Count; ++roomSequenceIndex)
                    {
                        var   roomSequence = roomSequences[roomSequenceIndex];
                        float posX0        = groupArea.X + sequenceWidth * roomSequenceIndex;
                        float posX1        = groupArea.X + sequenceWidth * (roomSequenceIndex + 1);
                        for (int i = 0; i < roomSequence.Count; ++i)
                        {
                            RelevantRoom room  = roomSequence[i];
                            float        posY0 = ToVisualY(groupArea, room.MaxDepth);
                            float        posY1 = ToVisualY(groupArea, room.MinDepth);

                            // HACK: if a rooms is full of walls (but why a designer should do this???) then
                            // MaxDepth or MinDepth can be int.MinValue or int.MaxValue and posY0 or posY1 get f****d...
                            // However I'm solving the issue elsewhere, this hack is here as a really last chance for
                            // the 0.0000000001% of the cases that could be wrong
                            if (Math.Abs(posY0) >= short.MaxValue || Math.Abs(posY1) >= short.MaxValue)
                            {
                                continue;
                            }

                            // Draw fill color for room
                            Brush      colorBrush = _roomsNormalBrush;
                            RectangleF roomRect   = new RectangleF(posX0, posY0, posX1 - posX0, posY1 - posY0);
                            if (room.Block != null && room.Block.Type != BlockType.Floor)
                            {
                                colorBrush = _roomsWallBrush;
                            }
                            using (var colorBrush2 = getRoomBrush(room.Room, colorBrush))
                                e.Graphics.FillRectangle(colorBrush2, roomRect);
                            if (!CheckRoom(room.MinDepth, room.MaxDepth))
                            {
                                e.Graphics.FillRectangle(_roomsOutsideOverdraw, roomRect);
                            }
                            if (room.Room.Locked)
                            {
                                e.Graphics.FillRectangle(_roomsLockedBrush, roomRect);
                            }

                            // Find portals on the selected sector
                            Pen belowPen = _roomBoundsPen;
                            if (room.Block != null && room.Block.FloorPortal != null)
                            {
                                Room portalRoom = room.Block.FloorPortal.AdjoiningRoom;
                                if (i - 1 >= 0 && roomSequence[i - 1].Room == portalRoom)
                                {
                                    belowPen = _portalPen;
                                }
                            }
                            Pen abovePen = _roomBoundsPen;
                            if (room.Block != null && room.Block.CeilingPortal != null)
                            {
                                Room portalRoom = room.Block.CeilingPortal.AdjoiningRoom;
                                if (i + 1 < roomSequence.Count && roomSequence[i + 1].Room == portalRoom)
                                {
                                    abovePen = _portalPen;
                                }
                            }

                            //Draw room borders
                            e.Graphics.DrawLine(belowPen, posX0, posY1, posX1, posY1);
                            e.Graphics.DrawLine(abovePen, posX0, posY0, posX1, posY0);
                            e.Graphics.DrawLine(_sequenceSeperatorPen, posX0, posY0, posX0, posY1);
                            e.Graphics.DrawLine(_sequenceSeperatorPen, posX1, posY0, posX1, posY1);
                        }
                    }
                }
            }

            // Draw outline around the groups
            for (int groupIndex = 0; groupIndex < GroupCount; ++groupIndex)
            {
                RectangleF groupArea = groupGetArea(barArea, groupIndex);
                e.Graphics.DrawRectangle(_outlinePen, groupArea);
            }
        }
コード例 #19
0
        private void Ruler_DrawVertPart(Graphics g, Font f, StringFormat df, float offset, float height)
        {
            float xoff, yoff, yinc, sinc;
            float mod;

            xoff = Design.PointsX(this.Width / 2 - 2);
            if (_IsMetric)
                mod = Design.PointsY(g.DpiY / 2.54f);
            else
                mod = Design.PointsY(g.DpiY);
            yinc = mod / _Intervals;
            float scroll = Design.PointsY(ScrollPosition);
            sinc = yoff = 0;
            if (scroll > offset)
                sinc += (yinc - scroll % yinc);

            // Fill in the background for the entire ruler
            //            RectangleF rf = new RectangleF(0, yoff + offset - scroll, this.Width, height);
            RectangleF rf = new RectangleF(0, offset - scroll, Design.PointsX(this.Width), height);
            if (rf.IntersectsWith(g.ClipBounds))
            {
                LinearGradientBrush lgb = new LinearGradientBrush(rf, BEGINCOLOR, ENDCOLOR, LinearGradientMode.Horizontal);
                g.FillRectangle(lgb, rf);
                lgb.Dispose();
            }
            else
                return;         // nothing to draw

            // Loop thru and draw the ruler
            float width = Design.PointsX(this.Width);
            while (sinc + offset + yoff - scroll < (offset + height) - scroll &&
                sinc + offset + yoff - scroll < g.ClipBounds.Bottom)
            {
                if (sinc + offset + yoff - scroll < g.ClipBounds.Top - 20)
                {   // we don't need to do anything here
                }
                else if (yoff % mod < .1f || Math.Abs((yoff % mod) - mod) < .1f)
                {
                    if (yoff != 0)      // Don't draw the 0
                    {
                        string l = string.Format("{0:0}", yoff / mod);
                        SizeF sz = g.MeasureString(l, f);

                        g.DrawString(l, f, Brushes.Black,
                            xoff - (sz.Width / 2), sinc+offset + yoff - (sz.Height / 2) - scroll, df);
                    }
                    g.DrawLine(Pens.Black, width, sinc + offset + yoff - scroll, width - 2, sinc+offset + yoff - scroll);
                }
                else
                {
                    g.DrawLine(Pens.Black, xoff, sinc + offset + yoff - scroll, xoff + 2, sinc+offset + yoff - scroll);
                }
                yoff += yinc;
            }
        }
コード例 #20
0
 private void Ruler_DrawVert(Graphics g)
 {
     StringFormat df = null;
     Font f = null;
     SolidBrush sb = null;           // brush for non-ruler portions of ruler
     SolidBrush bb = null;           // brush for drawing the areas next to band separator
     try
     {
         g.PageUnit = GraphicsUnit.Point;
         // create some drawing resources
         df = new StringFormat();
         df.FormatFlags |= StringFormatFlags.NoWrap;
         df.Alignment = StringAlignment.Near;
         f = new Font("Arial", 8, FontStyle.Regular);
         sb = new SolidBrush(GAPCOLOR);
         bb = new SolidBrush(Design.SepColor);
         // Go thru the regions
         float sp = Design.PointsY(this.ScrollPosition);
         // 1) Offset
         RectangleF rf;
         float off = 0;
         float offset = Design.PointsY(this.Offset);
         float width = Design.PointsX(this.Width);
         if (this.Offset > 0)
         {
             rf = new RectangleF(0, 0, width, offset); // scrolling doesn't affect offset
             if (rf.IntersectsWith(g.ClipBounds))
             {
                 LinearGradientBrush lgb = new LinearGradientBrush(rf, BEGINCOLOR, ENDCOLOR, LinearGradientMode.ForwardDiagonal);
                 g.FillRectangle(lgb, rf);
                 lgb.Dispose();
                 lgb = null;
     //                        g.FillRectangle(sb, rf);
             }
             off = offset;
         }
         // 2) PageHeader
         if (Design.PageHeaderHeight > 0)
         {
             Ruler_DrawVertPart(g, f, df, off, Design.PageHeaderHeight);
             off += Design.PageHeaderHeight;
         }
         // 3) PageHeader separator
         rf = new RectangleF(0, off-sp, width, Design.SepHeight);
         if (rf.IntersectsWith(g.ClipBounds))
             g.FillRectangle(bb, rf);
         off += Design.SepHeight;
         // 4) Body
         if (Design.BodyHeight > 0)
         {
             Ruler_DrawVertPart(g, f, df, off, Design.BodyHeight);
             off += Design.BodyHeight;
         }
         // 5) Body separator
         rf = new RectangleF(0, off - sp, width, Design.SepHeight);
         if (rf.IntersectsWith(g.ClipBounds))
             g.FillRectangle(bb, rf);
         off += Design.SepHeight;
         // 6) PageFooter
         if (Design.PageFooterHeight > 0)
         {
             Ruler_DrawVertPart(g, f, df, off, Design.PageFooterHeight);
             off += Design.PageFooterHeight;
         }
         // 7) PageFooter separator
         rf = new RectangleF(0, off - sp, width, Design.SepHeight);
         if (rf.IntersectsWith(g.ClipBounds))
             g.FillRectangle(bb, rf);
         off += Design.SepHeight;
         // 8) The rest to end
         rf = new RectangleF(0, off - sp, width, Design.PointsY(this.Height) - (off - sp));
         if (rf.IntersectsWith(g.ClipBounds))
             g.FillRectangle(sb, rf);
     }
     finally
     {
         if (df != null)
             df.Dispose();
         if (f != null)
             f.Dispose();
         if (sb != null)
             sb.Dispose();
         if (bb != null)
             bb.Dispose();
     }
 }
コード例 #21
0
        private void Ruler_DrawHorz(Graphics g)
        {
            float xoff, yoff, xinc;

            StringFormat drawFormat=null;
            Font f = null;
            LinearGradientBrush lgb=null;
            try
            {
                drawFormat = new StringFormat();
                drawFormat.FormatFlags |= StringFormatFlags.NoWrap;

                drawFormat.Alignment = StringAlignment.Near;
                float mod;
                yoff = this.Height/2 -2;
                mod = g.DpiX;
                if (_IsMetric)
                    mod = mod / 2.54f;
                xinc = mod / _Intervals;
                float scroll = ScrollPosition;
                if (scroll == 0)
                    xoff = 0;
                else
                    xoff = scroll + (xinc - scroll % xinc);

                RectangleF rf;
                if (Offset > 0) // Fill in the left gap; if any
                {
                    rf = new RectangleF(0, 0, Offset, this.Height);
                    if (rf.IntersectsWith(g.ClipBounds))
                    {
                        lgb = new LinearGradientBrush(rf, BEGINCOLOR, ENDCOLOR, LinearGradientMode.ForwardDiagonal);
                        g.FillRectangle(lgb, rf);
                        lgb.Dispose();
                        lgb = null;
            //                        g.FillRectangle(new SolidBrush(GAPCOLOR), rf);
                    }
                }

                // Fill in the background for the entire ruler
                rf = new RectangleF(this.Offset, 0, this.Width, this.Height);
                if (rf.IntersectsWith(g.ClipBounds))
                {
                    lgb = new LinearGradientBrush(rf, BEGINCOLOR, ENDCOLOR, LinearGradientMode.Vertical);
                    g.FillRectangle(lgb, rf);
                    lgb.Dispose();
                    lgb = null;
                }
                else      // nothing to draw
                    return;

                f = new Font("Arial", 8, FontStyle.Regular);

                // Loop thru and draw the ruler
                while (xoff - scroll < this.Width-Offset)
                {
            //        if (xoff % mod < .001f )
                    if (xoff % mod < .1f || Math.Abs((xoff % mod) - mod) < .1f)
                    {
                        if (xoff != 0)  // Don't draw the zero
                        {
                            string l = string.Format("{0:0}", xoff / mod);
                            SizeF sz = g.MeasureString(l, f);

                            g.DrawString(l, f, Brushes.Black,
                                Offset + xoff - (sz.Width / 2) - scroll, yoff - (sz.Height / 2), drawFormat);
                        }
                        g.DrawLine(Pens.Black, Offset + xoff - scroll, this.Height, Offset + xoff - scroll, this.Height - 2);
                    }
                    else
                    {
                        g.DrawLine(Pens.Black, Offset + xoff - scroll, yoff, Offset + xoff - scroll, yoff + 2);
                    }
                    xoff += xinc;
                }
            }
            finally
            {
                if (lgb != null)
                    lgb.Dispose();
                if (drawFormat != null)
                    drawFormat.Dispose();
                if (f != null)
                    f.Dispose();
            }
        }
コード例 #22
0
ファイル: PrintLabelDocument.cs プロジェクト: paopaofeng/dp2
        internal void DoPrintPage(
            IWin32Window owner,
            LabelParam label_param,
            string strStyle,
            PrintPageEventArgs e)
        {
            string strError = "";
            int nRet = 0;

            if (e.Cancel == true)
                return;

            bool bTestingGrid = false;
            if (StringUtil.IsInList("TestingGrid", strStyle) == true)
                bTestingGrid = true;


            int nYCount = 0;
            int nXCount = 0;

            double PageWidth = label_param.PageWidth;
            double PageHeight = label_param.PageHeight;
#if NO
            if (label_param.Landscape == true)
            {
                double nTemp = PageHeight;
                PageHeight = PageWidth;
                PageWidth = nTemp;
            }
#endif
#if NO
            if (e.PageSettings.Landscape == true)
            {
                double nTemp = PageHeight;
                PageHeight = PageWidth;
                PageWidth = nTemp;
            }
#endif

            int nPageWidth = e.PageBounds.Width;    // PageBounds 中已经是按照 Landscape 处理过的方向了
            if (PageWidth != 0)
                nPageWidth = (int)PageWidth;

            int nPageHeight = e.PageBounds.Height;
            if (PageHeight != 0)
                nPageHeight = (int)PageHeight;

            DecimalPadding PageMargins = RotatePadding(label_param.PageMargins, 
                e.PageSettings.Landscape);  // label_param.Landscape
#if NO
            // 垂直方向的个数
            nYCount = (e.PageBounds.Height - label_param.PageMargins.Top - label_param.PageMargins.Bottom)
                / label_param.Height;
            // 水平方向的个数
            nXCount = (e.PageBounds.Width - label_param.PageMargins.Left - label_param.PageMargins.Right)
            / label_param.Width;
#endif
            // 垂直方向的个数
            nYCount = (int)
                (
                (double)(nPageHeight - PageMargins.Top - PageMargins.Bottom)
                / (double)label_param.LabelHeight
                );
            // 水平方向的个数
            nXCount = (int)
                (
                (double)(nPageWidth - PageMargins.Left - PageMargins.Right)
                / (double)label_param.LabelWidth
                );

            int from = 0;
            int to = 0;
            bool bOutput = true;
            // 如果 e.PageSettings.PrinterSettings.FromPage == 0,会被当作打印第一页
            if (e.PageSettings.PrinterSettings.PrintRange == PrintRange.SomePages
                && e.PageSettings.PrinterSettings.FromPage >= 1)
            {
                from = e.PageSettings.PrinterSettings.FromPage;
                to = e.PageSettings.PrinterSettings.ToPage;

                // 交换,保证from为小
                if (from > to)
                {
                    int temp = to;
                    to = from;
                    from = temp;
                }

                if (this.m_nPageNo == 0)
                {
                    this.m_nPageNo = from;

                    Debug.Assert(this.m_nPageNo >= 1, "");
                    long nLabelCount = (nXCount * nYCount) * (this.m_nPageNo - 1);

                    // 从文件中跳过这么多label的内容行
                    for (int i = 0; i < nLabelCount; i++)
                    {
                        List<string> lines = null;
                        nRet = this.GetLabelLines(out lines,
                            out strError);
                        if (nRet == -1)
                            goto ERROR1;

                        if (nRet == 1)
                        {
                            e.Cancel = true;
                            return;
                        }
                    }
                }

                /*
                if (this.m_nPageNo >= from
                    && this.m_nPageNo <= to)
                {
                    bOutput = true;
                }
                else
                {
                    bOutput = false;
                }
                 * */
            }
            else
            {
                if (this.m_nPageNo == 0)
                    this.m_nPageNo = 1; // 一般性的初始化
            }


            // 加快运行速度
            float nXDelta = e.PageSettings.PrintableArea.Left;
            float nYDelta = e.PageSettings.PrintableArea.Top;

            /*
            if (this.PrintController.IsPreview == true)
            {
                nXDelta = 0;
                nYDelta = 0;
            }
             * */

            if (this.OriginAtMargins == true
                || this.PreviewMode == true)   // false
            {
                // true 如果图形起始于页面边距。否则起始于可打印区域
                nXDelta = 0;
                nYDelta = 0;
            }

            if (this.OriginPoint != null)
            {
                nXDelta -= this.OriginPoint.X;
                nYDelta -= this.OriginPoint.Y;
            }

#if NO
            float nPrintableWidth = e.PageSettings.PrintableArea.Width;
            float nPrintableHeight = e.PageSettings.PrintableArea.Height;
#endif


            if (this.IsDesignMode)
            {
#if NO
                Pen pen = new Pen(Color.Blue, (float)1);

                e.Graphics.DrawRectangle(pen,
                    0 + 1 - nXDelta,
                    0 + 1 - nYDelta,
                    e.PageBounds.Width - 2,
                    e.PageBounds.Height - 2);

                pen.Dispose();
#endif
                // 绘制整个纸张背景 白色
                using (Brush brushBack = new SolidBrush(Color.White))
                {
                    RectangleF rectPaper = new RectangleF(0 + 1 - nXDelta,
                        0 + 1 - nYDelta,
                        e.PageBounds.Width - 2,
                        e.PageBounds.Height - 2);
                    e.Graphics.FillRectangle(brushBack, rectPaper);
                }

#if NO
                // 绘制配置文件的页面区域
                if (PageHeight > 0 && PageWidth > 0)
                {
                    using (Brush brushBack = new SolidBrush(Color.FromArgb(128, Color.LightYellow)))
                    {
                        RectangleF rectPaper = new RectangleF(0 - nXDelta,
                            0 - nYDelta,
                            (float)PageWidth,
                            (float)PageHeight);
                        e.Graphics.FillRectangle(brushBack, rectPaper);
                    }
                }
#endif
            }

            // 绘制可打印区域
            // 鲜红色
            if (bTestingGrid == true && bOutput == true)
            {
                float nXOffs = 0;
                float nYOffs = 0;

                // 如果为正式打印,左上角(0,0)已经就是可以打印区域的左上角
                // 如果为preview模式,则左上角要向右向下移动,才能模拟出显示效果

#if NO
                if (this.OriginAtMargins == true
                    || this.PreviewMode == true)
                {
                    nXOffs = e.PageSettings.PrintableArea.Left;
                    nYOffs = e.PageSettings.PrintableArea.Top;
                }
#endif


                if (this.OriginPoint != null)
                {
                    nXOffs += this.OriginPoint.X;
                    nYOffs += this.OriginPoint.Y;
                }

                RectangleF rect = RotateRectangle(e.PageSettings.PrintableArea,
                    e.PageSettings.Landscape);  // label_param.Landscape

                if (this.OriginAtMargins == true
    || this.PreviewMode == true)
                {
                }
                else
                {
                    rect.X = 0;
                    rect.Y = 0;
                }

                rect.Offset(nXOffs, nYOffs);

                using (Pen pen = new Pen(Color.Red, (float)1))
                {
                    DrawFourAngel(
    e.Graphics,
    pen,
    rect,
    50);    // 半英寸
                }
            }

            // 加入变换
            e.Graphics.TranslateTransform(-nXDelta, -nYDelta);
            nXDelta = 0;
            nYDelta = 0;

            if (label_param.RotateDegree != 0)
            {
                float x_offs, y_offs;
                CenterMove(label_param.RotateDegree,
            (float)label_param.PageWidth,  // e.PageBounds.Width,
            (float)label_param.PageHeight, // e.PageBounds.Height,
            out x_offs,
            out y_offs);
                e.Graphics.TranslateTransform(x_offs, y_offs);
                e.Graphics.RotateTransform((float)label_param.RotateDegree);
            }

            if (this.IsDesignMode)
            {
                // 绘制配置文件的页面区域
                if (PageHeight > 0 && PageWidth > 0)
                {
                    using (Brush brushBack = new SolidBrush(Color.FromArgb(128, Color.LightYellow)))
                    {
                        RectangleF rectPaper = new RectangleF(0 - nXDelta,
                            0 - nYDelta,
                            (float)PageWidth,
                            (float)PageHeight);
                        e.Graphics.FillRectangle(brushBack, rectPaper);
                    }
                }
            }

            // 绘制内容区域边界(也就是排除了页面边空的中间部分)
            // 淡绿色
            if (bTestingGrid == true && bOutput == true)
            {
                using (Pen pen = new Pen(Color.FromArgb(0, 100, 0), (float)2)) // 3
                {

#if NO
                e.Graphics.DrawRectangle(pen,
                    PageMargins.Left - nXDelta,
                    PageMargins.Top - nYDelta,
                    e.PageBounds.Width - PageMargins.Left - PageMargins.Right,
                    e.PageBounds.Height - PageMargins.Top - PageMargins.Bottom);
#endif
                    e.Graphics.DrawRectangle(pen,
        (float)PageMargins.Left - nXDelta,
        (float)PageMargins.Top - nYDelta,
        (float)nPageWidth - (float)PageMargins.Left - (float)PageMargins.Right,
        (float)nPageHeight - (float)PageMargins.Top - (float)PageMargins.Bottom);

                }
            }

            bool bEOF = false;

            float y = (float)PageMargins.Top;
            // 每一行的循环
            for (int i = 0; i < nYCount; i++)
            {
                bool bDisplay = true;
                if (this.IsDesignMode == true)
                {
                    RectangleF rectLine = new RectangleF(
    (float)0 - nXDelta,
    (float)y - nYDelta,
    (float)label_param.LabelWidth * nXCount,
    (float)label_param.LabelHeight);
                    if (rectLine.Top > e.Graphics.ClipBounds.Bottom)
                    {
                        // Debug.WriteLine("break line loop at " + i.ToString());
                        break;  // 当前行在剪裁区域的下方,可以中断循环了
                    }
                    if (rectLine.IntersectsWith(e.Graphics.ClipBounds) == false)
                    {
                        // Debug.WriteLine("skip line " + i.ToString());
                        bDisplay = false;
                    }
                }
                float x = (float)PageMargins.Left;
                // 每一列的循环
                for (int j = 0; j < nXCount; j++)
                {
                    List<string> lines = null;
                    nRet = this.GetLabelLines(out lines,
                        out strError);
                    if (nRet == -1)
                        goto ERROR1;

                    if (nRet == 1)
                        bEOF = true;

                    if (bOutput == true  && bDisplay == true)
                    {
                        // 标签
                        RectangleF rectLabel = new RectangleF(
    (float)x - nXDelta,
    (float)y - nYDelta,
    (float)label_param.LabelWidth,
    (float)label_param.LabelHeight);

                        if (rectLabel.Left > e.Graphics.ClipBounds.Right)
                        {
                            // Debug.WriteLine("break label loop at i=" + i.ToString() + " j=" + j.ToString());
                            // 当前标签在剪裁区域的右方,可以不要显示后面的标签了
                            bDisplay = false;
                        }

                        if (this.IsDesignMode == false
                            || rectLabel.IntersectsWith(e.Graphics.ClipBounds) == true)
                        {
                            // Debug.WriteLine("i="+i.ToString()+" j="+j.ToString()+" rectLabel = "+rectLabel.ToString()+", clipbounds " + e.Graphics.ClipBounds.ToString());
                            // 标签内容区域
                            RectangleF rectContent = new RectangleF(
                                    (float)x + (float)label_param.LabelPaddings.Left - nXDelta,
                                    (float)y + (float)label_param.LabelPaddings.Top - nYDelta,
                                    (float)label_param.LabelWidth - (float)label_param.LabelPaddings.Left - (float)label_param.LabelPaddings.Right - 1,
                                    (float)label_param.LabelHeight - (float)label_param.LabelPaddings.Top - (float)label_param.LabelPaddings.Bottom - 1);


                            // 绘制标签边界
                            // 灰色
                            if (bTestingGrid == true)
                            {
                                // 标签白色背景
                                if (this.IsDesignMode == true)
                                {
                                    using (Brush brushBack = new SolidBrush(Color.FromArgb(200, Color.White)))
                                    {
                                        e.Graphics.FillRectangle(brushBack, rectLabel);
                                    }
                                }

                                // 标签边界
                                using (Pen pen = new Pen(Color.FromArgb(200, 200, 200), this.IsDesignMode ? (float)0.5 : (float)1))
                                {
                                    e.Graphics.DrawRectangle(pen,
                                        rectLabel.X,
                                        rectLabel.Y,
                                        rectLabel.Width,
                                        rectLabel.Height);
#if NO
                            e.Graphics.DrawRectangle(pen,
                                x - nXDelta,
                                y - nYDelta,
                                (float)label_param.LabelWidth,
                                (float)label_param.LabelHeight);
#endif

                                }


                                // 绘制标签内部文字区域边界
                                // 淡红色

                                using (Pen pen = new Pen(Color.FromArgb(255, 200, 200), this.IsDesignMode ? (float)0.5 : (float)1))
                                {
                                    e.Graphics.DrawRectangle(pen,
                                        rectContent.X,
                                        rectContent.Y,
                                        rectContent.Width,
                                        rectContent.Height);
#if NO
                            e.Graphics.DrawRectangle(pen,
                                (float)x + (float)label_param.LabelPaddings.Left - nXDelta,
                                (float)y + (float)label_param.LabelPaddings.Top - nYDelta,
                                (float)label_param.LabelWidth - (float)label_param.LabelPaddings.Left - (float)label_param.LabelPaddings.Right - 1,
                                (float)label_param.LabelHeight - (float)label_param.LabelPaddings.Top - (float)label_param.LabelPaddings.Bottom - 1);
#endif

                                }
                            }

#if NO
                        RectangleF clip = new RectangleF((float)x + (float)label_param.LabelPaddings.Left - nXDelta,
    (float)y + (float)label_param.LabelPaddings.Top - nYDelta,
    (float)label_param.LabelWidth - (float)label_param.LabelPaddings.Left - (float)label_param.LabelPaddings.Right,
    (float)label_param.LabelHeight - (float)label_param.LabelPaddings.Top - (float)label_param.LabelPaddings.Bottom);
#endif

                            using (Region old_clip = e.Graphics.Clip)
                            {
                                e.Graphics.IntersectClip(rectContent);

                                float y0 = 0;
                                for (int k = 0; k < lines.Count; k++)
                                {
                                    string strText = lines[k];

                                    LineFormat format = null;
                                    if (k < label_param.LineFormats.Count)
                                        format = label_param.LineFormats[k];

                                    Font this_font = null;
                                    bool bIsBarcodeFont = false;
                                    if (format != null && format.Font != null)
                                    {
                                        this_font = format.Font;
                                        bIsBarcodeFont = format.IsBarcodeFont;
                                    }
                                    else
                                    {
                                        this_font = label_param.Font;
                                        bIsBarcodeFont = label_param.IsBarcodeFont;
                                    }

                                    if (bIsBarcodeFont == true && string.IsNullOrEmpty(strText) == false)
                                        strText = "*" + strText + "*";

                                    float nLineHeight = this_font.GetHeight(e.Graphics);

                                    RectangleF rect = new RectangleF((float)x + (float)label_param.LabelPaddings.Left - nXDelta,
                                        (float)y + (float)label_param.LabelPaddings.Top + y0 - nYDelta,
                                        (float)label_param.LabelWidth - (float)label_param.LabelPaddings.Left - (float)label_param.LabelPaddings.Right,
                                        nLineHeight);

                                    bool bAbsLocation = false;
                                    // 行格式的 start 和 offset
                                    if (format != null)
                                    {
                                        if (double.IsNaN(format.StartX) == false)
                                            rect.X = (float)format.StartX;
                                        if (double.IsNaN(format.StartY) == false)
                                        {
                                            rect.Y = (float)format.StartY;
                                            bAbsLocation = true;    // Y 绝对定位后,行高度不参与累计
                                        }
                                        rect.Offset((float)format.OffsetX, (float)format.OffsetY);

                                        y0 += (float)format.OffsetY;    // Y 偏移后,累计值也跟着调整

                                    }

                                    StringFormat s_format = new StringFormat();
                                    if (format != null)
                                    {
                                        if (format.Align == "right")
                                            s_format.Alignment = StringAlignment.Far;
                                        else if (format.Align == "center")
                                            s_format.Alignment = StringAlignment.Center;
                                        else
                                            s_format.Alignment = StringAlignment.Near;

                                        s_format.Trimming = StringTrimming.EllipsisCharacter;
                                        // s_format.LineAlignment = StringAlignment.Center;
                                    }

                                    if (format != null && string.IsNullOrEmpty(format.BackColor) == false)
                                    {
                                        using (Brush brush = new SolidBrush(GetColor(format.BackColor)))
                                        {
                                            e.Graphics.FillRectangle(brush, rect);
                                        }
                                    }

                                    {
                                        Brush brushText = null;

                                        if (format != null && string.IsNullOrEmpty(format.ForeColor) == false)
                                        {
                                            brushText = new SolidBrush(GetColor(format.ForeColor));
                                        }
                                        else
                                            brushText = System.Drawing.Brushes.Black;

                                        e.Graphics.DrawString(strText,
                                            this_font,
                                            brushText,
                                            rect,
                                            s_format);

                                        if (brushText != System.Drawing.Brushes.Black)
                                            brushText.Dispose();
                                    }


                                    // 文字行区域边界
                                    // 黑色点
                                    if (bTestingGrid == true && label_param.LineSep > 0)
                                    {
                                        using (Pen pen = new Pen(Color.Black, (float)1))
                                        {
                                            // pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Custom;

#if NO
                                            e.Graphics.DrawRectangle(pen,
                                                rect.Left,
                                                rect.Top,
                                                rect.Width,
                                                rect.Height);
#endif
                                            pen.DashPattern = new float[] { 1F, 3F, 1F, 3F };
                                            e.Graphics.DrawLine(pen,
                                                new PointF(rect.Left, rect.Top),
                                                new PointF(rect.Right, rect.Top)
                                                );
                                            e.Graphics.DrawLine(pen,
                                                new PointF(rect.Left + 2, rect.Bottom),
                                                new PointF(rect.Right, rect.Bottom)
                                                );
                                        }
                                    }

                                    if (bAbsLocation == false)
                                        y0 += nLineHeight + (float)label_param.LineSep;
                                }

                                e.Graphics.Clip = old_clip;
                            } // end of using clip

                        } // end if IntersectsWith



                    } // end if bOutput == true


                    x += (float)label_param.LabelWidth;
                }

            CONTINUE_LINE:
                y += (float)label_param.LabelHeight;
            }

            // If more lines exist, print another page.
            if (bEOF == false)
            {
                if (e.PageSettings.PrinterSettings.PrintRange == PrintRange.SomePages)
                {
                    if (this.m_nPageNo >= to)
                    {
                        e.HasMorePages = false;
                        return;
                    }
                }
            }
            else
            {
                e.HasMorePages = false;
                return;
            }

            this.m_nPageNo++;
            e.HasMorePages = true;
            return;
        ERROR1:
            MessageBox.Show(owner, strError);
        }
コード例 #23
0
        void GetCenteredBlock()
        {
            //if (UICardPlace.Decelerating)
            //	return;

            var proposedContentOffset = UICardPlace.ContentOffset;
            float horizontalCenter = (float)(proposedContentOffset.X + (UICardPlace.Bounds.Size.Width / 2.0));

            RectangleF pointer = new RectangleF (horizontalCenter, 10, 10, 10);

            for (int i = 0; i < _words.Length; i++) {
                    if (pointer.IntersectsWith (_words [i].Frame)) {
                        ForceCenter (i);
                        break;
                    }
            }
        }
コード例 #24
0
ファイル: Spiral.cs プロジェクト: KuroiAme/Indexer
        //        PointF drawSpiralPoint (double scale, double revolutions, int centreX, int centreY, object st, int width, int heigh)
        //        {
        //            throw new NotImplementedException ();
        //        }
        public static RectangleF GetModuloRect(RectangleF currentRect, RectangleF outer, int ic)
        {
            //			const double scale = 0.01;
            //			//const double delta = 1;
            //			const int degreesPerIteration = 30;
            //			double revolutions = iterationCount * degreesPerIteration;
            //			int centreX = (int)center.X;
            //			int centreY = (int)center.Y;
            //
            //			int width = (int)frameSize.Width;
            //			int heigh = (int)frameSize.Height;
            //
            //			return drawSpiralPoint (scale, revolutions, centreX, centreY, st, width, heigh);

            PointF center = IndexerUtils.findcenter (outer);

            //			int direction = ic % 4;
            //
            //			if (direction == 0) { // NEGATIVE NEGATIVE
            //					currentRect = new RectangleF (center.X - ic, center.Y - ic, currentRect.Width, currentRect.Height);
            //				if(outer.IntersectsWith(currentRect)){
            //					return currentRect;
            //				}
            //			}
            //
            //			if (direction == 1) { // POSITIVE POSITIVE
            //					currentRect = new RectangleF (center.X + ic, center.X + ic, currentRect.Width, currentRect.Height);
            //				if(outer.IntersectsWith(currentRect)){
            //					return currentRect;
            //				}
            //			}
            //
            //			if (direction == 2) { // POSITIVE NEGATIVE
            //					currentRect = new RectangleF (center.X + ic, center.X - ic, currentRect.Width, currentRect.Height);
            //				if(outer.IntersectsWith(currentRect)){
            //					return currentRect;
            //				}
            //			}
            //
            //			if (direction == 3) { // NEGATIVE POSTIVE
            //					currentRect = new RectangleF (center.X - ic, center.X + ic, currentRect.Width, currentRect.Height);
            //				if(outer.IntersectsWith(currentRect)){
            //					return currentRect;
            //				}
            //			}

            //			if (direction == 0) { // NEGATIVE NEGATIVE
                currentRect = new RectangleF (center.X - ic, center.Y - ic, currentRect.Width, currentRect.Height);
                if(outer.IntersectsWith(currentRect)){
                    return currentRect;
                }
            //			}

            //			if (direction == 1) { // POSITIVE POSITIVE
                currentRect = new RectangleF (center.X + ic, center.X + ic, currentRect.Width, currentRect.Height);
                if(outer.IntersectsWith(currentRect)){
                    return currentRect;
                }
            //			}

            //			if (direction == 2) { // POSITIVE NEGATIVE
                currentRect = new RectangleF (center.X + ic, center.X - ic, currentRect.Width, currentRect.Height);
                if(outer.IntersectsWith(currentRect)){
                    return currentRect;
                }
            //			}

            //			if (direction == 3) { // NEGATIVE POSTIVE
                currentRect = new RectangleF (center.X - ic, center.X + ic, currentRect.Width, currentRect.Height);
                if(outer.IntersectsWith(currentRect)){
                    return currentRect;
                }
            //			}

            return GetModuloRect (currentRect, outer, ++ic);
        }
コード例 #25
0
ファイル: Tank.cs プロジェクト: efgefg0001/Tanks
        public Point Move(IField field)
        {
            var velocity = 0f;
            lock(velocityLock)
                velocity = Velocity;
            var location = new PointF(Location.X, Location.Y);
            velocity *= field.Time.TimeStep / field.Time.Interval;
            var vecV = Direction.Multiply(velocity);
            var step = field.Time.TimeStep;
            var endTime = field.Time.Interval + field.Time.TimeStep;
            var rectangles = field.StaticObjBoundaries;

            for (var time = 0f; time < endTime; time += step)
            {
                location = location.Add(vecV);
                var curLocRect = new RectangleF(location, Size);
                foreach (var rect in rectangles)
                    if (curLocRect.IntersectsWith(rect))
                    {
                        var intersectRect = RectangleF.Intersect(curLocRect, rect);//.Location;
                        var normal = GetNormal(intersectRect, rect);
                        var negDir = Direction.Negate();
                        Direction = negDir.Reflect(location, normal).Normalize();
                        vecV = Direction.Multiply(velocity);
                        location = location.Add(vecV);
                        curLocRect = new RectangleF(location, Size);
                        while (curLocRect.IntersectsWith(rect))
                        {
                            location = location.Add(vecV);
                            curLocRect = new RectangleF(location, Size);
                        }
                        break;
                    }
            }
            return location.ToPoint();
        }
コード例 #26
0
ファイル: D2dTimelineRenderer.cs プロジェクト: boshlong/ATF
 /// <summary>
 /// Finds hits on a key, given a picking rectangle</summary>
 /// <param name="key">Key</param>
 /// <param name="bounds">Bounding rectangle, computed during layout phase</param>
 /// <param name="pickRect">Picking rectangle</param>
 /// <param name="c">Drawing context</param>
 /// <returns>Type of hit</returns>
 protected virtual HitType Pick(IKey key, RectangleF bounds, RectangleF pickRect, Context c)
 {
     return bounds.IntersectsWith(pickRect) ? HitType.Key : HitType.None;
 }
コード例 #27
0
        public static void Draw(Block[,] grid, Vector2 positionTopLeft,ref RectangleF windowFrame,View view, float rotation = 0.0f,bool ForceRender = false)
        {
            short width = (short)grid.GetLength(0);
            short height = (short)grid.GetLength(1);
            //origin = zero
            Vector2[] vertices = new Vector2[4]
            {
                new Vector2(0,0),
                new Vector2(1,0),
                new Vector2(1,1),
                new Vector2(0,1),
            };
            GL.MatrixMode(MatrixMode.Texture);
            GL.LoadIdentity();
            if (rotation != 0)
            {
                var matrix = Matrix4.CreateTranslation(-0.5f, -0.5f, 0.0f) *
                          Matrix4.CreateFromAxisAngle(new Vector3(0, 0, 1), rotation) *
                          Matrix4.CreateTranslation(0.5f, 0.5f, 0.0f);
                GL.LoadMatrix(ref matrix);
            }
            GL.MatrixMode(MatrixMode.Modelview);
            byte h;
            RectangleF checking;
            for (short i = 0; i < width; i++)
            {
                for (short j = 0; j < height; j++)
                {
                    if (!ForceRender)
                    {
                        if ((i % view.TextureDensity == 0 && j % view.TextureDensity == 0))
                        {
                            //checking = new RectangleF((grid[i, j].PreciseLocation.X + positionTopLeft.X), (grid[i, j].PreciseLocation.Y + positionTopLeft.Y), 1.5f, 1.5f);
                            checking = new RectangleF(
                                (grid[i, j].PreciseLocation.X + positionTopLeft.X), (grid[i, j].PreciseLocation.Y + positionTopLeft.Y),
                                1f * view.Zoom, 1f * view.Zoom);
                            if (!windowFrame.IntersectsWith(checking))
                                continue;

                        }
                    }
                    GL.BindTexture(TextureTarget.Texture2D, grid[i,j].Texture(view.TextureSize).ID);
                    GL.Begin(PrimitiveType.Quads);
                    for (h = 0; h < 4; h++)
                    {
                        GL.TexCoord2(vertices[h]);
                        GL.Vertex2((vertices[h] + positionTopLeft + grid[i,j].PreciseLocation)*view.TextureSize);
                    }
                    GL.End();
                }
            }
        }
コード例 #28
0
ファイル: RoutingGrid.cs プロジェクト: ChrisMoreton/Test3
		/// <summary>
		/// mark obstacles and costs in the routing grid.
		/// </summary>
		private void markObstacles(RectangleF bounds,
			Arrow arrow, int cols, int rows)
		{
			RoutingOptions rop = flowChart.RoutingOptions;
			float gridSize = rop.GridSize;
			byte ccost = rop.CrossingCost;

			foreach (ChartObject obj in flowChart.Objects)
			{
				// if there is a crossing cost assigned, mark arrows in the route grid
				if (obj is Arrow && ccost > 0)
				{
					if (obj == arrow) continue;
					Arrow link = obj as Arrow;

					// at this time we handle only asPerpendicular links
					if (link.Style == ArrowStyle.Cascading)
					{
						PointF cp1 = link.ControlPoints[0];
						Point gp1 = new Point(
							(int)((cp1.X - bounds.Left) / gridSize),
							(int)((cp1.Y - bounds.Top) / gridSize));

						// iterate over all segments
						for (int i = 0; i < link.ControlPoints.Count - 1; ++i)
						{
							PointF cp2 = link.ControlPoints[i + 1];
							Point gp2 = new Point(
								(int)((cp2.X - bounds.Left) / gridSize),
								(int)((cp2.Y - bounds.Top) / gridSize));

							if (!gp1.Equals(gp2))
							{
								if (gp1.X == gp2.X)
								{
									// vertical segment
									if (gp1.X >= 0 && gp1.X < cols)
									{
										int miny = Math.Min(gp1.Y, gp2.Y);
										miny = Math.Max(0, miny);
										int maxy = Math.Max(gp1.Y, gp2.Y);
										maxy = Math.Min(rows - 1, maxy);
										for (int y = miny; y <= maxy; ++y)
											if (costGrid[gp1.X, y] < ccost) costGrid[gp1.X, y] = ccost;
									}
								}
								else
								{
									// horizontal segment
									if (gp1.Y >= 0 && gp1.Y < rows)
									{
										int minx = Math.Min(gp1.X, gp2.X);
										minx = Math.Max(0, minx);
										int maxx = Math.Max(gp1.X, gp2.X);
										maxx = Math.Min(cols - 1, maxx);
										for (int x = minx; x <= maxx; ++x)
											if (costGrid[x, gp1.Y] < ccost) costGrid[x, gp1.Y] = ccost;
									}
								}
							}

							gp1 = gp2;
						}
					}
					continue;
				}

				if (!(obj is Node))
					continue;

				Node node = obj as Node;
				if (!node.Obstacle)
					continue;
				if (node.MasterGroup != null && node.MasterGroup.MainObject == arrow)
					continue;

				RectangleF nodeRect = node.getRotatedBounds();

				if (bounds.IntersectsWith(nodeRect))
				{
					RectangleF intrRect = bounds;
					intrRect.Intersect(nodeRect);

					Point ptStart = new Point(
						(int)((intrRect.Left - bounds.Left) / gridSize),
						(int)((intrRect.Top - bounds.Top) / gridSize));
					Point ptEnd = new Point(
						(int)((intrRect.Right - bounds.Left) / gridSize),
						(int)((intrRect.Bottom - bounds.Top) / gridSize));

					if (ptStart.X < 0) ptStart.X = 0;
					if (ptStart.Y < 0) ptStart.Y = 0;
					if (ptEnd.X >= cols) ptEnd.X = cols - 1;
					if (ptEnd.Y >= rows) ptEnd.Y = rows - 1;

					// mark node interior as obstacle
					for (int c = ptStart.X; c <= ptEnd.X; ++c)
						for (int r = ptStart.Y; r <= ptEnd.Y; ++r)
							costGrid[c, r] = 255;

					// mark surrounding area with any cost assigned
					// going lineary down to the outside directions
					if (rop.NodeVicinityCost == 0) continue;
					for (int i = 1; i <= rop.NodeVicinitySize / gridSize; ++i)
					{
						byte cost = (byte)(rop.NodeVicinityCost / i);

						int minc = Math.Max(0, ptStart.X - i);
						int maxc = Math.Min(cols - 1, ptEnd.X + i);
						int minr = Math.Max(0, ptStart.Y - i);
						int maxr = Math.Min(rows - 1, ptEnd.Y + i);

						// top side
						int r = ptStart.Y - i;
						if (r >= 0)
						{
							for (int c = minc; c <= maxc; ++c)
								if (costGrid[c, r] < cost) costGrid[c, r] = cost;
						}

						// bottom side
						r = ptEnd.Y + i;
						if (r <= maxr)
						{
							for (int c = minc; c <= maxc; ++c)
								if (costGrid[c, r] < cost) costGrid[c, r] = cost;
						}

						// left side
						int cc = ptStart.X - i;
						if (cc >= 0)
						{
							for (r = minr; r <= maxr; ++r)
								if (costGrid[cc, r] < cost) costGrid[cc, r] = cost;
						}

						// right side
						cc = ptEnd.X + i;
						if (cc <= maxc)
						{
							for (r = minr; r <= maxr; ++r)
								if (costGrid[cc, r] < cost) costGrid[cc, r] = cost;
						}
					}
				}
			}
		}
コード例 #29
0
		protected override void OnPaint(PaintEventArgs pe)
		{
			float yPos       = 1;
			float itemHeight = ItemHeight;
			// Maintain aspect ratio
			int imageWidth = (int)(itemHeight * imageList.ImageSize.Width / imageList.ImageSize.Height);
			
			int curItem = firstItem;
			Graphics g  = pe.Graphics;
			while (curItem < completionData.Length && yPos < Height) {
				RectangleF drawingBackground = new RectangleF(1, yPos, Width - 2, itemHeight);
				if (drawingBackground.IntersectsWith(pe.ClipRectangle)) {
					// draw Background
					if (curItem == selectedItem) {
						g.FillRectangle(SystemBrushes.Highlight, drawingBackground);
					} else {
						g.FillRectangle(SystemBrushes.Window, drawingBackground);
					}
					
					// draw Icon
					int   xPos   = 0;
					if (imageList != null && completionData[curItem].ImageIndex < imageList.Images.Count) {
						g.DrawImage(imageList.Images[completionData[curItem].ImageIndex], new RectangleF(1, yPos, imageWidth, itemHeight));
						xPos = imageWidth;
					}
					
					// draw text
					if (curItem == selectedItem) {
						g.DrawString(completionData[curItem].Text, Font, SystemBrushes.HighlightText, xPos, yPos);
					} else {
						g.DrawString(completionData[curItem].Text, Font, SystemBrushes.WindowText, xPos, yPos);
					}
				}
				
				yPos += itemHeight;
				++curItem;
			}
			g.DrawRectangle(SystemPens.Control, new Rectangle(0, 0, Width - 1, Height - 1));
		}
コード例 #30
0
 /// <summary>
 /// Calculates which edge of a rectangle the point intersects with, within a certain limit
 /// </summary>
 private static Edge IntersectElementEdge(RectangleF screen, PointF pt, float limit)
 {
     RectangleF ptRect = new RectangleF(pt.X - limit, pt.Y - limit, 2F * limit, 2F * limit);
     if ((pt.X >= screen.X - limit && pt.X <= screen.X + limit) && (pt.Y >= screen.Y - limit && pt.Y <= screen.Y + limit))
         return Edge.TopLeft;
     if ((pt.X >= screen.X + screen.Width - limit && pt.X <= screen.X + screen.Width + limit) && (pt.Y >= screen.Y - limit && pt.Y <= screen.Y + limit))
         return Edge.TopRight;
     if ((pt.X >= screen.X + screen.Width - limit && pt.X <= screen.X + screen.Width + limit) && (pt.Y >= screen.Y + screen.Height - limit && pt.Y <= screen.Y + screen.Height + limit))
         return Edge.BottomRight;
     if ((pt.X >= screen.X - limit && pt.X <= screen.X + limit) && (pt.Y >= screen.Y + screen.Height - limit && pt.Y <= screen.Y + screen.Height + limit))
         return Edge.BottomLeft;
     if (ptRect.IntersectsWith(new RectangleF(screen.X, screen.Y, screen.Width, 1F)))
         return Edge.Top;
     if (ptRect.IntersectsWith(new RectangleF(screen.X, screen.Y, 1F, screen.Height)))
         return Edge.Left;
     if (ptRect.IntersectsWith(new RectangleF(screen.X, screen.Y + screen.Height, screen.Width, 1F)))
         return Edge.Bottom;
     if (ptRect.IntersectsWith(new RectangleF(screen.X + screen.Width, screen.Y, 1F, screen.Height)))
         return Edge.Right;
     return Edge.None;
 }
コード例 #31
0
ファイル: Node.cs プロジェクト: vanzheng/CShareCodeSample
        private PointF GetDelta(RectangleF bounds1, RectangleF bounds2)
        {
            float dx = 0;
            float dy = 0;

            //  return new PointF(bounds2.X - bounds1.X, bounds2.Y - bounds1.Y);

            if (bounds2.IntersectsWith(bounds1))
                return new PointF(4, 1);

            if (bounds2.Right < bounds1.Left)
                dx = bounds2.Right - bounds1.Left;

            if (bounds2.Left > bounds1.Right)
                dx = bounds2.Left - bounds1.Right;

            if (bounds2.Bottom < bounds1.Top)
                dy = bounds2.Bottom - bounds1.Top;

            if (bounds2.Top > bounds1.Bottom)
                dy = bounds2.Top - bounds1.Bottom;

            return new PointF(dx, dy);
        }
コード例 #32
0
ファイル: GameServer.cs プロジェクト: NTaylorMullen/BombRMan
            private void MoveExact(int x, int y)
            {
                float effectiveX = x / (POWER * 1f),
                      effectiveY = y / (POWER * 1f);

                var actualX = (int)Math.Floor((float)(x + (POWER / 2)) / POWER);
                var actualY = (int)Math.Floor((float)(y + (POWER / 2)) / POWER);
                var targets = GetHitTargets();
                var sourceLeft = effectiveX * _map.TileSize;
                var sourceTop = effectiveY * _map.TileSize;
                var sourceRect = new RectangleF(sourceLeft, sourceTop, _map.TileSize, _map.TileSize);
                var collisions = new List<Point>();
                var possible = new List<Point>();

                foreach (var t in targets)
                {
                    int targetX = actualX + t.X,
                        targetY = actualY + t.Y;

                    var targetRect = new RectangleF(targetX * _map.TileSize, targetY * _map.TileSize, _map.TileSize, _map.TileSize);
                    var movable = Movable(targetX, targetY);
                    var intersects = sourceRect.IntersectsWith(targetRect);

                    if (!movable && intersects)
                    {
                        collisions.Add(new Point(targetX, targetY));
                    }
                    else
                    {
                        possible.Add(new Point(targetX, targetY));
                    }
                }

                if (collisions.Count == 0)
                {
                    SetDirection(DirectionX, DirectionY);

                    X = actualX;
                    Y = actualY;

                    ExactX = x;
                    ExactY = y;
                }
                else
                {
                    var candidates = new List<Tuple<int, int, Point>>();
                    Tuple<int, int, Point> candidate = null;
                    var p1 = new Point(actualX + DirectionX, actualY);
                    var p2 = new Point(actualX, actualY + DirectionY);
                    foreach (var nextMove in possible)
                    {
                        if (p1.Equals(nextMove))
                        {
                            candidates.Add(Tuple.Create(DirectionX, 0, p1));
                        }

                        if (p2.Equals(nextMove))
                        {
                            candidates.Add(Tuple.Create(0, DirectionY, p2));
                        }
                    }

                    if (candidates.Count == 1)
                    {
                        candidate = candidates[0];
                    }
                    else if (candidates.Count == 2)
                    {
                        int minDistance = Int32.MaxValue;
                        for (int i = 0; i < candidates.Count; ++i)
                        {
                            var targetCandidate = candidates[i];
                            int xs = (ExactX - candidates[i].Item3.X * POWER);
                            int ys = (ExactY - candidates[i].Item3.Y * POWER);
                            int distance = xs * xs + ys * ys;

                            if (distance < minDistance)
                            {
                                minDistance = distance;
                                candidate = targetCandidate;
                            }
                        }
                    }

                    if (candidate != null)
                    {
                        var diffX = candidate.Item3.X * POWER - ExactX;
                        var diffY = candidate.Item3.Y * POWER - ExactY;
                        var absX = Math.Abs(diffX);
                        var absY = Math.Abs(diffY);
                        int effectiveDirectionX = 0;
                        int effectiveDirectionY = 0;

                        if (absX == 100)
                        {
                            effectiveDirectionX = 0;
                        }
                        else
                        {
                            effectiveDirectionX = Math.Sign(diffX);
                        }

                        if (absY == 100)
                        {
                            effectiveDirectionY = 0;
                        }
                        else
                        {
                            effectiveDirectionY = Math.Sign(diffY);
                        }

                        if (effectiveDirectionX == 0 && effectiveDirectionY == 0)
                        {
                            effectiveDirectionX = candidate.Item1;
                            effectiveDirectionY = candidate.Item2;
                        }

                        SetDirection(effectiveDirectionX, effectiveDirectionY);

                        ExactX += DELTA * effectiveDirectionX;
                        X = actualX;

                        ExactY += DELTA * effectiveDirectionY;
                        Y = actualY;
                    }
                    else
                    {
                        var diffY = (collisions[0].Y * POWER - ExactY);
                        var diffX = (collisions[0].X * POWER - ExactX);
                        var absX = Math.Abs(diffX);
                        var absY = Math.Abs(diffY);
                        int effectiveDirectionX = 0;
                        int effectiveDirectionY = 0;

                        if (absX >= 35 && absX < 100)
                        {
                            effectiveDirectionX = -Math.Sign(diffX);
                        }

                        if (absY >= 35 && absY < 100)
                        {
                            effectiveDirectionY = -Math.Sign(diffY);
                        }

                        SetDirection(effectiveDirectionX, effectiveDirectionY);

                        ExactX += DELTA * effectiveDirectionX;
                        ExactY += DELTA * effectiveDirectionY;
                    }
                }
            }
コード例 #33
0
        // render all the objects in a page (or any composite object
        private void ProcessPage(Graphics g, IEnumerable p, RectangleF clipRect, bool bHitList)
        {
            // TODO: (Peter) Support can grow and can shrink
            foreach (PageItem pi in p)
            {
                if (pi is PageTextHtml)
                {	// PageTextHtml is actually a composite object (just like a page)
                    if (SelectTool && bHitList)
                    {
                        RectangleF hr = new RectangleF(PixelsX(pi.X + _left - _hScroll), PixelsY(pi.Y + _top - _vScroll),
                                                                            PixelsX(pi.W), PixelsY(pi.H));
                        _HitList.Add(new HitListEntry(hr, pi));
                    }
                    ProcessHtml(pi as PageTextHtml, g, clipRect, bHitList);
                    continue;
                }

                if (pi is PageLine)
                {
                    PageLine pl = pi as PageLine;
                    DrawLine(pl.SI.BColorLeft, pl.SI.BStyleLeft, pl.SI.BWidthLeft,
                        g, PixelsX(pl.X + _left - _hScroll), PixelsY(pl.Y + _top - _vScroll),
                        PixelsX(pl.X2 + _left - _hScroll), PixelsY(pl.Y2 + _top - _vScroll));
                    continue;
                }

                RectangleF rect = new RectangleF(PixelsX(pi.X + _left - _hScroll), PixelsY(pi.Y + _top - _vScroll),
                                                                    PixelsX(pi.W), PixelsY(pi.H));

                // Maintain the hit list
                if (bHitList)
                {
                    if (SelectTool)
                    {   // we need all PageText and PageImage items that have been displayed
                        if (pi is PageText || pi is PageImage)
                        {
                            _HitList.Add(new HitListEntry(rect, pi));
                        }
                    }
                    // Only care about items with links and tips
                    else if (pi.HyperLink != null || pi.BookmarkLink != null || pi.Tooltip != null)
                    {
                        HitListEntry hle;
                        if (pi is PagePolygon)
                            hle = new HitListEntry(pi as PagePolygon, _left - _hScroll, _top - _vScroll, this);
                        else
                            hle = new HitListEntry(rect, pi);
                        _HitList.Add(hle);
                    }
                }

                if ((pi is PagePolygon) || (pi is PageCurve))
                { // intentionally empty; polygon's rectangles aren't calculated
                }
                else if (!rect.IntersectsWith(clipRect))
                    continue;

                if (pi.SI.BackgroundImage != null)
                {	// put out any background image
                    PageImage i = pi.SI.BackgroundImage;
                    DrawImageBackground(i, pi.SI, g, rect);
                }

                if (pi is PageText)
                {
                    // TODO: enable can shrink, can grow
                    // 2005 spec file, page 9, in the text box has
                    // CanGrow and CanShrink
                    PageText pt = pi as PageText;
                    DrawString(pt, g, rect);
                }
                else if (pi is PageImage)
                {
                    PageImage i = pi as PageImage;
                    DrawImage(i, g, rect);
                }
                else if (pi is PageRectangle)
                {
                    this.DrawBackground(g, rect, pi.SI);
                }
                else if (pi is PageEllipse)
                {
                    PageEllipse pe = pi as PageEllipse;
                    DrawEllipse(pe, g, rect);
                }
                else if (pi is PagePie)
                {
                    PagePie pp = pi as PagePie;
                    DrawPie(pp, g, rect);
                }
                else if (pi is PagePolygon)
                {
                    PagePolygon ppo = pi as PagePolygon;
                    FillPolygon(ppo, g, rect);
                }
                else if (pi is PageCurve)
                {
                    PageCurve pc = pi as PageCurve;
                    DrawCurve(pc.SI.BColorLeft, pc.SI.BStyleLeft, pc.SI.BWidthLeft,
                        g, pc.Points, pc.Offset, pc.Tension);
                }

                DrawBorder(pi, g, rect);
            }
        }
コード例 #34
0
ファイル: PageDrawing.cs プロジェクト: mnisl/OD
		// render all the objects in a page (or any composite object
		private void ProcessPage(Graphics g, IEnumerable p, RectangleF clipRect, bool bHitList)
		{
			foreach (PageItem pi in p)
			{
				if (pi is PageTextHtml)
				{	// PageTextHtml is actually a composite object (just like a page)
					ProcessHtml(pi as PageTextHtml, g, clipRect, bHitList);
					continue;
				}

				if (pi is PageLine)
				{
					PageLine pl = pi as PageLine;
					DrawLine(pl.SI.BColorLeft, pl.SI.BStyleLeft, pl.SI.BWidthLeft, 
						g, PixelsX(pl.X + _left - _hScroll), PixelsY(pl.Y + _top - _vScroll), 
						PixelsX(pl.X2 + _left - _hScroll), PixelsY(pl.Y2 + _top - _vScroll));
					continue;
				}

				RectangleF rect = new RectangleF(PixelsX(pi.X + _left - _hScroll), PixelsY(pi.Y + _top - _vScroll), 
																	PixelsX(pi.W), PixelsY(pi.H));

				// Maintain the hit list
				if (bHitList)	
				{
					// Only care about items with links and tips
					if (pi.HyperLink != null || pi.BookmarkLink != null || pi.Tooltip != null)
					{
						_HitList.Add(new HitListEntry(rect, pi));
					}
				}

				if (!rect.IntersectsWith(clipRect))
					continue;

				if (pi.SI.BackgroundImage != null)
				{	// put out any background image
					PageImage i = pi.SI.BackgroundImage;
					DrawImage(i, g, rect);
				}
				
				if (pi is PageText)
				{
					PageText pt = pi as PageText;
					DrawString(pt, g, rect);
				}
				else if (pi is PageImage)
				{
					PageImage i = pi as PageImage;
					DrawImage(i, g, rect);
				}
				else if (pi is PageRectangle)
				{
					this.DrawBackground(g, rect, pi.SI);
				}

				DrawBorder(pi, g, rect);
			}
		}