Example #1
0
        protected override void OnSizeChanged(EventArgs e)
        {
            base.OnSizeChanged(e);
            Rectangle rect = ClientRectangle;

            if (rect.Width <= 0 || rect.Height <= 0)
            {
                return;
            }

            if (Alignment != DockAlignment.Left && Alignment != DockAlignment.Right)
            {
                return;
            }

            _foregroundBrush?.Dispose();
            using (var path = new GraphicsPath())
            {
                path.AddRectangle(rect);
                _foregroundBrush = new PathGradientBrush(path)
                {
                    CenterColor    = _horizontalBrush.Color,
                    SurroundColors = _verticalSurroundColors
                };
            }
        }
Example #2
0
 private void MakeForegroundBrush(Rectangle rect)
 {
     _foregroundBrush?.Dispose();
     using (var path = new GraphicsPath())
     {
         path.AddRectangle(rect);
         _foregroundBrush = new PathGradientBrush(path)
         {
             CenterColor    = _horizontalBrush.Color,
             SurroundColors = _verticalSurroundColors
         };
     }
 }
Example #3
0
 public void Dispose()
 {
     _Brush?.Dispose();
     foreach (var conection in _Conections)
     {
         if (conection != null)
         {
             conection.Dispose();
         }
     }
 }
Example #4
0
        /// <summary>
        /// Initialize with a new max chart level.
        /// </summary>
        /// <param name="maxLevel"></param>
        public void InitializeVariables(int maxLevel)
        {
            _maxLevel = maxLevel;
            _maxR     = Math.Min(Width, Height) / 2;
            _xm       = _maxR + 1;
            _ym       = _maxR + 1;
            _maxR    -= 15;

            _step = (int)Math.Round(maxLevel / 25d);
            if (_step < 1)
            {
                _step = 1;
            }
            _step *= 5;

            _maxPs = new List <Point>();
            _ps    = new List <Point>();
            int r = 0;

            for (int s = 0; s < DisplayedStats; s++)
            {
                double angle = AnglePerStat * s - AngleOffset;
                _ps.Add(new Point(_xm + (int)(r * Math.Cos(angle)), _ym + (int)(r * Math.Sin(angle))));

                _maxPs.Add(new Point(_xm + (int)(_maxR * Math.Cos(angle)), _ym + (int)(_maxR * Math.Sin(angle))));
            }

            // color gradient
            GraphicsPath path = new GraphicsPath();

            path.AddEllipse(_xm - _maxR, _ym - _maxR, 2 * _maxR + 1, 2 * _maxR + 1);
            _grBrushBg?.Dispose();
            _grBrushFg?.Dispose();
            _grBrushBg = new PathGradientBrush(path);
            _grBrushFg = new PathGradientBrush(path);

            Color[] colorsBg =
            {
                Color.FromArgb(0,  90, 0),
                Color.FromArgb(90, 90, 0),
                Color.FromArgb(90,  0, 0)
            };

            Color[] colorsFg =
            {
                Color.FromArgb(0,   180, 0),
                Color.FromArgb(180, 180, 0),
                Color.FromArgb(180,   0, 0)
            };

            float[] relativePositions = { 0, 0.45f, 1 };

            ColorBlend colorBlendBg = new ColorBlend
            {
                Colors    = colorsBg,
                Positions = relativePositions
            };

            _grBrushBg.InterpolationColors = colorBlendBg;

            ColorBlend colorBlendFg = new ColorBlend
            {
                Colors    = colorsFg,
                Positions = relativePositions
            };

            _grBrushFg.InterpolationColors = colorBlendFg;

            SetLevels();
        }
Example #5
0
        protected override void OnPaint(PaintEventArgs pevent)
        {
            Graphics g = pevent.Graphics;

            g.FillRectangle(SystemBrushes.Control, 0, 0, Width, Height);
            g.SmoothingMode = SmoothingMode.AntiAlias;

            // Create painting objects
            Brush b = new SolidBrush(this.ForeColor);

            // Create Rectangle To Limit brush area.
            Rectangle rect = new Rectangle(0, 0, Width, Height);

            LinearGradientBrush linearBrush = null;

            if (Enabled)
            {
                linearBrush = new LinearGradientBrush(rect,
                                                      gradientStart,
                                                      gradientEnd,
                                                      _rotation);
            }
            else
            {
                linearBrush = new LinearGradientBrush(rect,
                                                      Color.SlateGray,
                                                      Color.DarkGray,
                                                      _rotation);
            }
            LinearGradientBrush highlightBrush =
                new LinearGradientBrush(rect,
                                        highGradientStart,
                                        highGradientEnd,
                                        _rotation);

            path      = new GraphicsPath();
            innerPath = new GraphicsPath();
            float  textX     = Width / 2;
            float  textY     = Height / 2;
            Region cliphover = Region;

            switch (Rotation)
            {
            case 0:
            {
                int      h  = Height - 1;
                int      w  = Width - 1;
                int      wa = w - arrowHeadWidth;
                int      h1 = (int)(h * (1 - arrowBaseHeight) / 2.0f);
                PointF[] la =
                {
                    new PointF(1,  h1),
                    new PointF(wa, h1),
                    new PointF(wa,      1),
                    new PointF(w,  h / 2),
                    new PointF(wa, h),
                    new PointF(wa, h - h1),
                    new PointF(1,  h - h1),
                    new PointF(1,  h1)
                };
                path.AddLines(la);
                PointF[] la2 =
                {
                    new PointF(0,      h1 - 1),
                    new PointF(wa - 1, h1 - 1),
                    new PointF(wa - 1,          0),
                    new PointF(w + 1,  h / 2),
                    new PointF(wa - 1, h + 1),
                    new PointF(wa - 1, h - h1 + 1),
                    new PointF(0,      h - h1 + 1),
                    new PointF(0,      h1 - 1)
                };
                innerPath.AddLines(la2);
                cliphover = new Region(new Rectangle(0, 0, hoverWidth, Height));
            }
            break;

            case 90:
            {
                int      h  = Height - 1;
                int      w  = Width - 1;
                int      ha = h - arrowHeadWidth + 1;
                int      w1 = (int)(w * (1 - arrowBaseHeight) / 2.0f);
                PointF[] la =
                {
                    new PointF(w1,      1),
                    new PointF(w1,     ha),
                    new PointF(1,      ha),
                    new PointF(w / 2,  h),
                    new PointF(w,      ha),
                    new PointF(w - w1, ha),
                    new PointF(w - w1,  1),
                    new PointF(w1, 1)
                };
                path.AddLines(la);
                PointF[] la2 =
                {
                    new PointF(w1 - 1,          0),
                    new PointF(w1 - 1,     ha - 1),
                    new PointF(0,          ha - 1),
                    new PointF(w / 2,      h + 1),
                    new PointF(w + 1,      ha - 1),
                    new PointF(w - w1 + 1, ha - 1),
                    new PointF(w - w1 + 1,      0),
                    new PointF(w1 - 1, 0)
                };
                innerPath.AddLines(la2);
                cliphover = new Region(new Rectangle(0, 0, Width, hoverWidth));
            }
            break;

            case 180:
            {
                int      h  = Height - 1;
                int      w  = Width - 1;
                int      wa = arrowHeadWidth + 1;
                int      h1 = (int)(h * (1 - arrowBaseHeight) / 2.0f);
                PointF[] la =
                {
                    new PointF(w,  h1),
                    new PointF(wa, h1),
                    new PointF(wa,      1),
                    new PointF(1,  h / 2),
                    new PointF(wa, h),
                    new PointF(wa, h - h1),
                    new PointF(w,  h - h1),
                    new PointF(w,  h1)
                };
                path.AddLines(la);
                PointF[] la2 =
                {
                    new PointF(w + 1,  h1 - 1),
                    new PointF(wa - 1, h1 - 1),
                    new PointF(wa - 1,          0),
                    new PointF(0,      h / 2),
                    new PointF(wa - 1, h + 1),
                    new PointF(wa - 1, h - h1 + 1),
                    new PointF(w + 1,  h - h1 + 1),
                    new PointF(w + 1,  h1 - 1)
                };
                innerPath.AddLines(la2);
            }
                cliphover = new Region(new Rectangle(Width - hoverWidth, 0, hoverWidth, Height));
                break;

            case 270:
            {
                int      h  = Height - 1;
                int      w  = Width - 1;
                int      ha = arrowHeadWidth + 1;
                int      w1 = (int)(w * (1 - arrowBaseHeight) / 2.0f);
                PointF[] la =
                {
                    new PointF(w1,     h),
                    new PointF(w1,     ha),
                    new PointF(1,      ha),
                    new PointF(w / 2,   1),
                    new PointF(w,      ha),
                    new PointF(w - w1, ha),
                    new PointF(w - w1, h),
                    new PointF(w1,     h)
                };
                path.AddLines(la);
                PointF[] la2 =
                {
                    new PointF(w1 - 1,     h + 1),
                    new PointF(w1 - 1,     ha + 1),
                    new PointF(0,          ha - 1),
                    new PointF(w / 2,           0),
                    new PointF(w + 1,      ha + 1),
                    new PointF(w - w1 + 1, ha + 1),
                    new PointF(w - w1 + 1, h + 1),
                    new PointF(w1 - 1,     h + 1)
                };
                innerPath.AddLines(la2);

                cliphover = new Region(new Rectangle(0, Height - hoverWidth, Width, hoverWidth));
            }
            break;
            }
            //this.Region = new Region(innerPath); // Set shape for hit detection
            Brush             fontBrush = Brushes.Black;
            PathGradientBrush pgbrush   = new PathGradientBrush(innerPath);

            pgbrush.CenterPoint    = new Point(75, 75);
            pgbrush.CenterColor    = Color.White;
            pgbrush.SurroundColors = new Color[] { this.ForeColor };
            Pen p = new Pen(borderColor, 1);

            g.FillPath(linearBrush, path);
            Region clip = g.Clip;

            g.Clip = cliphover;
            g.FillPath(highlightBrush, path);
            // Draw seperations
            string[] va = possibleValues.Split(';');
            g.Clip = new Region(path);
            switch (_rotation)
            {
            case 0: {
                for (int i = 0; i < va.Length - 1; i++)
                {
                    int pos = (i + 1) * Width / va.Length;
                    g.DrawLine(Pens.DarkGray, pos, 0, pos, Height);
                }
            }
            break;

            case 180:
            {
                for (int i = 0; i < va.Length - 1; i++)
                {
                    int pos = Width - (i + 1) * Width / va.Length;
                    g.DrawLine(Pens.DarkGray, pos, 0, pos, Height);
                }
            }
            break;

            case 90:
            {
                for (int i = 0; i < va.Length - 1; i++)
                {
                    int pos = (i + 1) * Height / va.Length;
                    g.DrawLine(Pens.DarkGray, 0, pos, Width, pos);
                }
            }
            break;

            case 270:
            {
                for (int i = 0; i < va.Length - 1; i++)
                {
                    int pos = Height - (i + 1) * Height / va.Length;
                    g.DrawLine(Pens.DarkGray, 0, pos, Width, pos);
                }
            }
            break;
            }
            g.Clip = clip;
            g.DrawPath(p, path);
            SizeF fsize = g.MeasureString(title, drawFont);

            textX -= fsize.Width / 2;
            textY -= fsize.Height / 2;
            g.DrawString(title, drawFont, fontBrush, textX, textY);
            // Dispose of painting objects
            b.Dispose();
            p.Dispose();
            pgbrush.Dispose();
            linearBrush.Dispose();
            highlightBrush.Dispose();
        }
Example #6
0
        /// <summary>
        /// Handles the drawing code for linear gradient paths.
        /// </summary>
        /// <param name="g"></param>
        /// <param name="gp"></param>
        public override void FillPath(Graphics g, GraphicsPath gp)
        {
            RectangleF bounds = Bounds;

            if (bounds.IsEmpty)
            {
                bounds = gp.GetBounds();
            }
            if (bounds.Width == 0 || bounds.Height == 0)
            {
                return;
            }
            //also don't draw gradient for very small polygons
            if (bounds.Width < 0.01 || bounds.Height < 0.01)
            {
                return;
            }
            if (_gradientType == GradientType.Linear)
            {
                LinearGradientBrush b  = new LinearGradientBrush(bounds, _colors[0], _colors[_colors.Length - 1], (float)-_angle);
                ColorBlend          cb = new ColorBlend();
                cb.Positions          = _positions;
                cb.Colors             = _colors;
                b.InterpolationColors = cb;
                g.FillPath(b, gp);
                b.Dispose();
            }
            else if (_gradientType == GradientType.Circular)
            {
                GraphicsPath round  = new GraphicsPath();
                PointF       center = new PointF(bounds.X + bounds.Width / 2, bounds.Y + bounds.Height / 2);
                float        x      = (float)(center.X - Math.Sqrt(2) * bounds.Width / 2);
                float        y      = (float)(center.Y - Math.Sqrt(2) * bounds.Height / 2);
                float        w      = (float)(bounds.Width * Math.Sqrt(2));
                float        h      = (float)(bounds.Height * Math.Sqrt(2));
                RectangleF   circum = new RectangleF(x, y, w, h);
                round.AddEllipse(circum);
                PathGradientBrush pgb = new PathGradientBrush(round);
                ColorBlend        cb  = new ColorBlend();
                cb.Colors               = _colors;
                cb.Positions            = _positions;
                pgb.InterpolationColors = cb;
                g.FillPath(pgb, gp);
                pgb.Dispose();
            }
            else if (_gradientType == GradientType.Rectangular)
            {
                GraphicsPath rect   = new GraphicsPath();
                PointF[]     points = new PointF[5];
                PointF       center = new PointF(bounds.X + bounds.Width / 2, bounds.Y + bounds.Height / 2);
                double       a      = bounds.Width / 2;
                double       b      = bounds.Height / 2;
                double       angle  = _angle;
                if (angle < 0)
                {
                    angle = 360 + angle;
                }
                angle = angle % 90;
                angle = 2 * (Math.PI * angle / 180);
                double x = a * Math.Cos(angle);
                double y = -b - a * Math.Sin(angle);
                points[0] = new PointF((float)x + center.X, (float)y + center.Y);
                x         = a + b * Math.Sin(angle);
                y         = b * Math.Cos(angle);
                points[1] = new PointF((float)x + center.X, (float)y + center.Y);
                x         = -a *Math.Cos(angle);

                y         = b + a * Math.Sin(angle);
                points[2] = new PointF((float)x + center.X, (float)y + center.Y);
                x         = -a - b * Math.Sin(angle);
                y         = -b *Math.Cos(angle);

                points[3] = new PointF((float)x + center.X, (float)y + center.Y);
                points[4] = points[0];
                rect.AddPolygon(points);
                PathGradientBrush pgb = new PathGradientBrush(rect);
                ColorBlend        cb  = new ColorBlend();
                cb.Colors               = _colors;
                cb.Positions            = _positions;
                pgb.InterpolationColors = cb;
                g.FillPath(pgb, gp);
                pgb.Dispose();
            }
        }
Example #7
0
        /// <summary>
        /// Renders the control to an image
        /// </summary>
        private void drawControl(Graphics g, bool on)
        {
            // Is the bulb on or off
            Color lightColor = (on) ? Color : Color.FromArgb(150, DarkColor);
            Color darkColor  = (on) ? DarkColor : DarkDarkColor;

            // Calculate the dimensions of the bulb
            int width  = Width - (Padding.Left + Padding.Right);
            int height = Height - (Padding.Top + Padding.Bottom);
            // Diameter is the lesser of width and height
            int diameter = Math.Min(width, height);

            // Subtract 1 pixel so ellipse doesn't get cut off
            diameter = Math.Max(diameter - 1, 1);

            // Draw the background ellipse
            var rectangle = new Rectangle(Padding.Left, Padding.Top, diameter, diameter);

            g.FillEllipse(darkColor, rectangle);

            // Draw the glow gradient
            var path = new GraphicsPath();

            path.AddEllipse(rectangle);
            var pathBrush = new PathGradientBrush(path);

            pathBrush.CenterColor    = lightColor;
            pathBrush.SurroundColors = new[] { Color.FromArgb(0, lightColor) };
            g.SetHighQuality();
            g.FillEllipse(pathBrush, rectangle);
            pathBrush.Dispose();

            // Draw the white reflection gradient
            var offset    = Convert.ToInt32(diameter * .15F);
            var diameter1 = Convert.ToInt32(rectangle.Width * .8F);
            var whiteRect = new Rectangle(rectangle.X - offset, rectangle.Y - offset, diameter1, diameter1);
            var path1     = new GraphicsPath();

            path1.AddEllipse(whiteRect);
            var pathBrush1 = new PathGradientBrush(path);

            pathBrush1.CenterColor    = _reflectionColor;
            pathBrush1.SurroundColors = _surroundColor;
            g.SetHighQuality();
            g.FillEllipse(pathBrush1, whiteRect);
            pathBrush1.Dispose();

            // Draw the border
            g.SetClip(ClientRectangle);
            g.SetHighQuality();

            if (On)
            {
                using (Pen pn = new Pen(Color.FromArgb(85, Color.Black), 1F))
                {
                    g.DrawEllipse(pn, rectangle);
                }
            }

            g.SetDefaultQuality();
        }
        /// <summary>Cleans up any unmanaged GDI+ resources used during painting.</summary>
        protected override void Dispose(bool disposing)
        {
            try
            {
                // Get the interpolation thread out of a loop
                IsInterpolationActive = false;

                if (InterpolationThread != null)
                {
#if Framework20 && !PocketPC
                    if (!InterpolationWaitHandle.SafeWaitHandle.IsInvalid)
#else
                    if (InterpolationWaitHandle.Handle != new IntPtr(-1))
#endif
                    { InterpolationWaitHandle.Set(); }

                    // Abort the painting thread
                    //if (!InterpolationThread.Join(500))
                    {
                        try
                        {
                            InterpolationThread.Abort();
                        }
                        catch
                        {
                        }
                    }
                }

#if Framework20 && !PocketPC
                if (!InterpolationWaitHandle.SafeWaitHandle.IsInvalid)
#else
                if (InterpolationWaitHandle.Handle != new IntPtr(-1))
#endif
                {
                    try
                    {
                        InterpolationWaitHandle.Close();
                    }
                    catch (ObjectDisposedException)
                    {
                    }
                }

#if !PocketPC
                if (GlassReflectionBrush != null)
                {
                    try
                    {
                        GlassReflectionBrush.Dispose();
                    }
                    catch (ObjectDisposedException)
                    {
                    }
                }
                if (GlassShadowBrush != null)
                {
                    try
                    {
                        GlassShadowBrush.Dispose();
                    }
                    catch (ObjectDisposedException)
                    {
                    }
                }
                if (GlassShadowPath != null)
                {
                    try
                    {
                        GlassShadowPath.Dispose();
                    }
                    catch (ObjectDisposedException)
                    {
                    }
                }
#endif
            }
            catch
            {
                throw;
            }
            finally
            {
                base.Dispose(disposing);
            }
        }
Example #9
0
        /// <summary>
        /// ボタンの表面描画
        /// </summary>
        /// <param name="g"></param>
        private void DrawButtonSurface(Graphics g)
        {
            // 描画品質設定
            SetSmoothMode(g);

            // 変数初期化
            int offset     = shadowSize;
            int w          = this.Width - cornerR;
            int h          = this.Height - cornerR;
            int harfHeight = (int)(this.Height / 2);

            // 影用のパス初期化
            GraphicsPath shadowPath = null;

            if (shadowSize > 0)
            {
                shadowPath = GetShadowPath();
            }

            // ボタンの表面のパス初期化
            GraphicsPath graphPath = new GraphicsPath();

            graphPath.AddArc(offset, offset, cornerR, cornerR, 180, 90);
            graphPath.AddArc(w - offset, offset, cornerR, cornerR, 270, 90);
            graphPath.AddArc(w - offset, h - offset, cornerR, cornerR, 0, 90);
            graphPath.AddArc(offset, h - offset, cornerR, cornerR, 90, 90);
            graphPath.CloseFigure();

            // ボタンのハイライト部分のパス初期化
            offset += 1;
            //cornerR -= 1;
            GraphicsPath graphPath2 = new GraphicsPath();

            graphPath2.AddArc(offset, offset, cornerR, cornerR, 180, 90);
            graphPath2.AddArc(w - offset, offset, cornerR, cornerR, 270, 90);
            graphPath2.AddLine(this.Width - offset, offset + (int)(cornerR / 2), this.Width - offset, harfHeight);
            graphPath2.AddLine(offset, harfHeight, offset, harfHeight);
            graphPath2.CloseFigure();


            // 影用のブラシ初期化
            PathGradientBrush shadowBrush = null;

            if (shadowSize > 0)
            {
                shadowBrush = GetShadowBrush(shadowPath);
            }

            // ボタンの表面用のブラシ初期化
            Brush fillBrush2 = new SolidBrush(surfaceColor);

            // ボタンのハイライト部分用のブラシ初期化
            LinearGradientBrush fillBrush = new LinearGradientBrush(new Point(0, 0),
                                                                    new Point(0, harfHeight + 1),
                                                                    Color.FromArgb(255, highLightColor),
                                                                    Color.FromArgb(0, surfaceColor));

            // 影 → 表面 → ハイライトの順番でパスを塗る
            if (shadowSize > 0)
            {
                g.FillPath(shadowBrush, shadowPath);
            }
            g.FillPath(fillBrush2, graphPath);
            g.FillPath(fillBrush, graphPath2);

            // ボタンの文字列描画
            DrawText(g);

            // 後処理
            if (shadowSize > 0)
            {
                shadowPath.Dispose();
            }
            graphPath.Dispose();
            graphPath2.Dispose();

            if (shadowSize > 0)
            {
                shadowBrush.Dispose();
            }
            fillBrush.Dispose();
            fillBrush2.Dispose();
        }
Example #10
0
        private void _Paint(object sender, PaintEventArgs e)
        {
            Bitmap   bmp = new Bitmap(_fWindow.Width, _fWindow.Height);
            Graphics g   = Graphics.FromImage(bmp);

            g.SmoothingMode     = SmoothingMode.AntiAlias;
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            g.Clear(Color.Transparent);
            // Draw shadow.
            g.FillPath(new SolidBrush(Color.FromArgb(63, 0, 0, 0)), _gpShadow);
            // Button background.
            Rectangle           rect   = new Rectangle(0, 0, _fWindow.Width, 30);
            LinearGradientBrush bgLine = new LinearGradientBrush(rect, Color.White, Color.Black, LinearGradientMode.Vertical);

            bgLine.InterpolationColors = Renderer.Button.NormalBlend();
            g.FillPath(bgLine, _gp);
            bgLine.Dispose();
            // Icon background
            GraphicsPath gp = new GraphicsPath();

            rect.X      = (int)(25 + (25 * Math.Sqrt(2) / 2)) - 50;
            rect.Y      = (int)(15 + (25 * Math.Sqrt(2) / 2)) - 50;
            rect.Width  = 100;
            rect.Height = 100;
            gp.AddEllipse(rect);
            PathGradientBrush bg = new PathGradientBrush(gp);

            bg.InterpolationColors = Renderer.Button.NormalBlend();
            g.FillEllipse(bg, _iconRect);
            bg.Dispose();
            gp.Dispose();
            // Draw the icon.
            if (_owner != null)
            {
                if (_owner.Icon != null)
                {
                    g.DrawIcon(_owner.Icon, new Rectangle(10, 0, 30, 30));
                }
            }
            // Draw the hosts.
            foreach (ItemHost ih in _hosts)
            {
                ih.draw(g);
            }
            // Draw outline.
            g.DrawPath(Ai.Renderer.Button.NormalBorderPen(), _gp);
            g.Dispose();
            // Drawing the bitmap into floating window.
            float fTrans = (_hover ? (float)_alphaHover / 255f : (float)_alphaLeave / 255f);

            float[][]       ptsArray = { new float[] { 1, 0, 0,      0, 0 },
                                         new float[]       { 0, 1, 0,      0, 0 },
                                         new float[]       { 0, 0, 1,      0, 0 },
                                         new float[]       { 0, 0, 0, fTrans, 0 },
                                         new float[]       { 0, 0, 0,      0, 1 } };
            ColorMatrix     clrMatrix     = new ColorMatrix(ptsArray);
            ImageAttributes imgAttributes = new ImageAttributes();

            imgAttributes.SetColorMatrix(clrMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
            e.Graphics.Clear(Color.Transparent);
            e.Graphics.DrawImage(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height),
                                 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel, imgAttributes);
            bmp.Dispose();
        }
Example #11
0
        protected override void OnPaint(PaintEventArgs pe)
        {
            base.OnPaint(pe);

            if (!_bShow)
            {
                return;
            }
            Font         stateFont = new Font("Arial", 10, FontStyle.Bold, GraphicsUnit.Point);
            StringFormat strFormat = new StringFormat
            {
                Alignment     = StringAlignment.Center,
                LineAlignment = StringAlignment.Center
            };
            Pen   borderPen    = new Pen(Color.ForestGreen, 1);
            Pen   redPen       = new Pen(Color.Red, 2);
            Pen   connectorPen = new Pen(Color.FromArgb(0x33, 0x00, 0x33), 1);
            Brush arrowBrush   = new SolidBrush(Color.FromArgb(0x33, 0x00, 0x33));

            foreach (Selectable _selectable in _selectables)
            {
                CurvedStateConnector curvedConnector = null;
                if (_selectable is StateConnector)
                {
                    var connector = _selectable as StateConnector;
                    if (connector.Label.IsSelected)
                    {
                        Pen labelBorderPen = new Pen(Color.DarkRed, 1.5f)
                        {
                            DashStyle = DashStyle.Dash
                        };
                        var labelRect = connector.Label.GetRect(_automatGraphics);
                        _automatGraphics.DrawRectangle(labelBorderPen, labelRect.Left,
                                                       labelRect.Top, labelRect.Width, labelRect.Height);
                        labelBorderPen.Dispose();
                    }
                    Pen pen = connector.IsSelected ? redPen : connectorPen;
                    if (_selectable is CurvedStateConnector)
                    {
                        curvedConnector = _selectable as CurvedStateConnector;
                    }
                    if (curvedConnector != null &&
                        curvedConnector.ControlPoints[0] != _InvalidPoint &&
                        curvedConnector.ControlPoints[1] != _InvalidPoint)
                    {
                        _automatGraphics.DrawBezier(pen, curvedConnector.SourceState.Position,
                                                    curvedConnector.ControlPoints[0],
                                                    curvedConnector.ControlPoints[1],
                                                    curvedConnector.DestinationState.Position);
                        _automatGraphics.DrawString(curvedConnector.Label.Text, ConnectorLabel.LabelFont,
                                                    Brushes.Brown, connector.Label.Position);
                    }
                    else
                    {
                        _automatGraphics.DrawLine(pen, connector.SourceState.Position,
                                                  connector.DestinationState.Position);
                        _automatGraphics.DrawString(connector.Label.Text, ConnectorLabel.LabelFont,
                                                    Brushes.Brown, connector.Label.Position);
                    }
                    if (connector.ArrowPoints != null)
                    {
                        _automatGraphics.DrawLine(pen, connector.ArrowPoints[0],
                                                  connector.ArrowPoints[1]);
                        _automatGraphics.DrawLine(pen, connector.ArrowPoints[0],
                                                  connector.ArrowPoints[2]);
                    }
                }
                else if (_selectable is State)
                {
                    var          state = _selectable as State;
                    GraphicsPath gp    = new GraphicsPath();
                    gp.AddEllipse(state.BoundingRect);
                    var boundColor = (_selectable == _hilightState && _t1 >= 0 &&
                                      _t1 <= 255) ? _paramColor :
                                     Color.FromArgb(0xCC, 0x66, 0xFF);
                    Color[] colors =
                    {
                        boundColor,                       // dark green
                        Color.FromArgb(0xCC, 0xCC, 0xFF), // aqua
                        Color.FromArgb(0xCC, 0xFF, 0xFF)
                    };                                    // blue

                    float[] relativePositions =
                    {
                        0f,    // Dark green is at the boundary of the triangle.
                        0.58f, // Aqua is 40 percent of the way from the boundary
                               // to the center point.
                        1.0f
                    }; // Blue is at the center point.

                    ColorBlend colorBlend = new ColorBlend();
                    colorBlend.Colors    = colors;
                    colorBlend.Positions = relativePositions;

                    PathGradientBrush grd = new PathGradientBrush(gp);
                    //{
                    //    SurroundColors = new Color[] { Color.FromArgb(0xCC, 0x33, 0xCC) },
                    //    CenterColor = Color.FloralWhite
                    //};
                    grd.InterpolationColors = colorBlend;
                    _automatGraphics.FillEllipse(grd, state.BoundingRect);
                    _automatGraphics.DrawString(state.Label, stateFont, Brushes.DarkSlateBlue,
                                                state.BoundingRect, strFormat);
                    Pen stateBorderPen = state.IsSelected ? redPen : borderPen;
                    _automatGraphics.DrawEllipse(stateBorderPen, state.BoundingRect);
                    if (IsFinalState(state))
                    {
                        Pen markPen = new Pen(Color.Maroon, 2);
                        var newRect = state.BoundingRect;
                        newRect.Inflate(3, 3);
                        _automatGraphics.DrawEllipse(markPen, newRect);
                        markPen.Dispose();
                    }
                    grd.Dispose();
                    gp.Dispose();
                }
            }
            if (_bCurve)
            {
                if (_curveControlPoints[0] != InvalidPoint)
                {
                    OnPaintHandle(_curveControlPoints[0]);
                }
                if (_curveControlPoints[1] != InvalidPoint)
                {
                    OnPaintHandle(_curveControlPoints[1]);
                }
            }
            OnAnimatePaint(_automatGraphics);
            pe.Graphics.DrawImage(_automatBitmap, DisplayRectangle, DisplayRectangle,
                                  GraphicsUnit.Pixel);
            stateFont.Dispose();
            strFormat.Dispose();
            borderPen.Dispose();
            redPen.Dispose();
            connectorPen.Dispose();
            arrowBrush.Dispose();
        }
Example #12
0
        private void button2_Click(object sender, EventArgs e)
        {
            /*
             * Создает новый объект Graphics из указанного дескриптора окна.
             * public static Graphics FromHwnd(
             *      IntPtr hwnd
             * )
             */
            Graphics gr = Graphics.FromHwnd(this.Handle);

            gr.DrawLine(new Pen(Color.Green), 10, 50, 10, 200); // рисуем на форме

            Graphics gr1 = Graphics.FromHwnd(label1.Handle);

            gr1.DrawLine(new Pen(Color.Green, 5.0f), 20, 10, 90, 10); // рисуем на статике

            /*
             * Рисует прямоугольник, который определен парой координат, шириной и высотой.
             * public void DrawRectangle(
             *      Pen pen, // Структура Pen, определяющая цвет, ширину и стиль прямоугольника.
             *      int x, // Координата X верхнего левого угла прямоугольника для рисования.
             *      int y, // Координата Y верхнего левого угла прямоугольника для рисования.
             *      int width, // Ширина прямоугольника для рисования.
             *      int height // Высота прямоугольника для рисования.
             * )
             */
            using (Pen p = new Pen(Color.Red, 4f))
            {
                p.DashStyle = DashStyle.DashDotDot;
                gr.DrawRectangle(p, 160, 100, 100, 100); // отрисовываем контур прямоугольника штриховой линией
            }


            // Определяет кисть одного цвета. Кисти используются для заливки графических фигур,
            // таких как прямоугольники, эллипсы, круги, многоугольники и контуры.
            SolidBrush brush = new SolidBrush(Color.Blue);

            /*
             * Заполняет внутреннюю часть прямоугольника, который определен парой координат, шириной и высотой.
             * public void FillRectangle(
             * Brush brush, // Объект Brush, определяющий параметры заливки.
             * int x, // Координата X верхнего левого угла прямоугольника для заливки.
             * int y, // Координата Y верхнего левого угла прямоугольника для заливки.
             * int width, // Ширина прямоугольника для заливки.
             * int height // Высота прямоугольника для заливки.
             * )
             */
            gr.FillRectangle(brush, 300, 10, 100, 100); // заполняем прямоугольник синей кистью

            // Задает прямоугольную кисть со стилем штриховки, основным цветом и цветом фона.
            HatchBrush hatch_brush = new HatchBrush(HatchStyle.ZigZag, Color.Green, Color.Tomato);

            /*
             * Заполняет внутреннюю часть эллипса, определяемого ограничивающим прямоугольником, заданным с помощью пары координат, ширины и высоты.
             * public void FillEllipse(
             *      Brush brush, //  Объект Brush, определяющий параметры заливки.
             *      int x, // Координата X верхнего левого угла ограничивающего прямоугольника, который определяет эллипс.
             *      int y, // Координата Y верхнего левого угла ограничивающего прямоугольника, который определяет эллипс.
             *      int width, // Ширина ограничивающего прямоугольника, определяющего эллипс.
             *      int height // Высота ограничивающего прямоугольника, определяющего эллипс.
             * )
             */
            gr.FillEllipse(hatch_brush, 300, 120, 100, 100); // заполняем прямоугольник узорчатой кистью

            using (Pen p = new Pen(hatch_brush, 10))
            {
                gr.DrawEllipse(p, 450, 10, 100, 100); // отрисовываем контур круга
            }

            Image        img     = Image.FromFile("fon2.bmp");
            TextureBrush texture = new TextureBrush(img);

            gr.FillRectangle(texture, 450, 120, 100, 100); // заполняем прямоугольник текстурой

            LinearGradientBrush gradient = new LinearGradientBrush(new Point(12, 12),
                                                                   new Point(110, 110), Color.Red, Color.Black);

            gr.FillRectangle(gradient, 600, 10, 100, 100); // заполняем прямоугольник градиентной заливкой

            Point[] pts = new Point[6] {
                new Point(600, 150), new Point(640, 130), new Point(680, 140), new Point(700, 200), new Point(680, 230), new Point(620, 200)
            };

            // Инкапсулирует объект Brush, заполняющий градиентом внутреннюю область объекта GraphicsPath
            PathGradientBrush path = new PathGradientBrush(pts);

            /*
             * Заполняет внутреннюю часть многоугольника, определяемого массивом точек, заданных структурами Point.
             * public void FillPolygon(
             *         Brush brush, // Объект Brush, определяющий параметры заливки.
             *         Point[] points, // Массив структур Point, которые представляют вершины закрашиваемого многоугольника.
             * )
             */
            gr.FillPolygon(path, pts);

            // Освобождаем системные ресурсы
            brush.Dispose();
            path.Dispose();
            img.Dispose();
            texture.Dispose();
            gradient.Dispose();
            gr1.Dispose();
            gr.Dispose();
        }