Example #1
0
        private void Cleanup()
        {
            isRunning = false;

            renderThread?.Join();

            tripleBuffer?.Dispose();

            stringFormat?.Dispose();
            fontCategoryNames?.Dispose();
            fontTeamNames?.Dispose();
            fontScores?.Dispose();
            penGridLines?.Dispose();
            brushTeamNames?.Dispose();
            brushScores?.Dispose();
            bitmapScores?.Dispose();

            if (brushesFireworks != null)
            {
                foreach (Brush brush in brushesFireworks)
                {
                    brush?.Dispose();
                }
            }
            if (brushesCategories != null)
            {
                foreach (Brush brush in brushesCategories)
                {
                    brush?.Dispose();
                }
            }
        }
Example #2
0
            private void DrawXLabelArea(Graphics graph)
            {
                Font         font         = null;
                SolidBrush   solidBrush   = null;
                StringFormat stringFormat = null;
                Pen          pen          = null;

                try
                {
                    font                   = new Font(this._fontFamily, 7f);
                    solidBrush             = new SolidBrush(this._fontColor);
                    stringFormat           = new StringFormat();
                    pen                    = new Pen(this._fontColor);
                    stringFormat.Alignment = StringAlignment.Center;
                    graph.DrawLine(pen, this._xOrigin, this._yOrigin + this._graphHeight, this._xOrigin + this._graphWidth, this._yOrigin + this._graphHeight);
                    float y    = this._yOrigin + this._graphHeight + 2f;
                    float num  = this._barWidth + this._spaceBtwBars;
                    int   num2 = 0;
                    foreach (ChartItem dataPoint in base.DataPoints)
                    {
                        float      x = this._xOrigin + (float)num2 * num;
                        RectangleF layoutRectangle = new RectangleF(x, y, num, (float)font.Height);
                        string     s = this._displayLegend ? dataPoint.Label : dataPoint.Description;
                        graph.DrawString(s, font, solidBrush, layoutRectangle, stringFormat);
                        num2++;
                    }
                }
                finally
                {
                    font?.Dispose();
                    solidBrush?.Dispose();
                    stringFormat?.Dispose();
                    pen?.Dispose();
                }
            }
Example #3
0
        public void Stop()
        {
            _timer?.Dispose();
            _timer = null;

            _font?.Dispose();
            _format?.Dispose();
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                format?.Dispose();
                format = null;
            }

            base.Dispose(disposing);
        }
Example #5
0
	protected override void OnPaint (PaintEventArgs args)
	{
		Graphics g = args.Graphics;

		SolidBrush brush = new SolidBrush (ForeColor);
		StringFormat sformat = new StringFormat ();
		sformat.FormatFlags = StringFormatFlags.LineLimit;
		g.DrawString ("WeShouldIncludeWhiteSpaces", Font, brush, new Rectangle (0, 0, 55, 100),
				sformat);
		brush.Dispose ();
		sformat.Dispose ();
	}
Example #6
0
            private void DrawBars(Graphics graph)
            {
                SolidBrush   solidBrush   = null;
                Font         font         = null;
                StringFormat stringFormat = null;

                try
                {
                    solidBrush             = new SolidBrush(this._fontColor);
                    font                   = new Font(this._fontFamily, 7f);
                    stringFormat           = new StringFormat();
                    stringFormat.Alignment = StringAlignment.Center;
                    int num = 0;
                    foreach (ChartItem dataPoint in base.DataPoints)
                    {
                        using (SolidBrush brush = new SolidBrush(dataPoint.ItemColor))
                        {
                            float num2 = (dataPoint.SweepSize == 0f) ? 2f : dataPoint.SweepSize;
                            float num3 = this._yOrigin + this._graphHeight - num2;
                            graph.FillRectangle(brush, this._xOrigin + dataPoint.StartPos + (this._barWidth / 2f - 8f), num3, 16f, num2);
                            if (this._displayBarData)
                            {
                                float      x = this._xOrigin + (float)num * (this._barWidth + this._spaceBtwBars);
                                float      y = num3 - 2f - (float)font.Height;
                                RectangleF layoutRectangle = new RectangleF(x, y, this._barWidth + this._spaceBtwBars, (float)font.Height);
                                float      value           = dataPoint.Value;
                                object     s;
                                if (!(value.ToString(CultureInfo.InvariantCulture) == "0.0"))
                                {
                                    value = dataPoint.Value;
                                    s     = value.ToString(CultureInfo.InvariantCulture);
                                }
                                else
                                {
                                    s = "0";
                                }
                                graph.DrawString((string)s, font, solidBrush, layoutRectangle, stringFormat);
                            }
                            num++;
                        }
                    }
                }
                finally
                {
                    solidBrush?.Dispose();
                    font?.Dispose();
                    stringFormat?.Dispose();
                }
            }
Example #7
0
        protected override void Dispose(bool disposing)
        {
            if (!IsDisposed)
            {
                try
                {
                    if (disposing)
                    {
                        _stringFormat?.Dispose();

                        _clearAllCache();
                    }
                }
                finally
                {
                    base.Dispose(disposing);
                }
            }
        }
Example #8
0
            public override Bitmap Draw()
            {
                int          perimeter    = this._perimeter;
                Rectangle    rect         = new Rectangle(0, 0, perimeter, perimeter - 1);
                Bitmap       bitmap       = new Bitmap(perimeter + this._legendWidth, perimeter);
                Graphics     graphics     = null;
                StringFormat stringFormat = null;
                SolidBrush   solidBrush   = null;

                try
                {
                    graphics     = Graphics.FromImage(bitmap);
                    stringFormat = new StringFormat();
                    graphics.FillRectangle(new SolidBrush(this._backgroundColor), 0, 0, perimeter + this._legendWidth, perimeter);
                    stringFormat.Alignment = StringAlignment.Far;
                    for (int i = 0; i < this._chartItems.Count; i++)
                    {
                        ChartItem chartItem = (ChartItem)this._chartItems[i];
                        using (solidBrush = null)
                        {
                            solidBrush = new SolidBrush(chartItem.ItemColor);
                            graphics.FillPie(solidBrush, rect, chartItem.StartPos, chartItem.SweepSize);
                            graphics.FillRectangle(solidBrush, perimeter + 125, i * this._legendFontHeight + 15, 10, 10);
                            graphics.DrawString(chartItem.Label, new Font(this._legendFontStyle, this._legendFontSize), new SolidBrush(Color.Black), (float)(perimeter + 125 + 20), (float)(i * this._legendFontHeight + 13));
                            graphics.DrawString(chartItem.Value.ToString("C"), new Font(this._legendFontStyle, this._legendFontSize), new SolidBrush(Color.Black), (float)(perimeter + 125 + 200), (float)(i * this._legendFontHeight + 13), stringFormat);
                        }
                    }
                    graphics.DrawEllipse(new Pen(this._borderColor, 2f), rect);
                    graphics.DrawRectangle(new Pen(this._borderColor, 1f), perimeter + 125 - 10, 10, 220, this._chartItems.Count * this._legendFontHeight + 25);
                    graphics.DrawString("Total", new Font(this._legendFontStyle, this._legendFontSize, FontStyle.Bold), new SolidBrush(Color.Black), (float)(perimeter + 125 + 30), (float)((this._chartItems.Count + 1) * this._legendFontHeight), stringFormat);
                    graphics.DrawString(this._total.ToString("C"), new Font(this._legendFontStyle, this._legendFontSize, FontStyle.Bold), new SolidBrush(Color.Black), (float)(perimeter + 125 + 200), (float)((this._chartItems.Count + 1) * this._legendFontHeight), stringFormat);
                    graphics.SmoothingMode = SmoothingMode.AntiAlias;
                }
                finally
                {
                    stringFormat?.Dispose();
                    graphics?.Dispose();
                }
                return(bitmap);
            }
Example #9
0
            private void DrawLegend(Graphics graph)
            {
                Font         font         = null;
                SolidBrush   solidBrush   = null;
                StringFormat stringFormat = null;
                Pen          pen          = null;

                try
                {
                    font                   = new Font(this._fontFamily, 9f);
                    solidBrush             = new SolidBrush(this._fontColor);
                    stringFormat           = new StringFormat();
                    pen                    = new Pen(this._fontColor);
                    stringFormat.Alignment = StringAlignment.Near;
                    float num     = this._xOrigin + this._graphWidth + 6f;
                    float yOrigin = this._yOrigin;
                    float num2    = num + 5f;
                    float x       = num2 + 10f + 5f;
                    float num3    = 0f;
                    int   num4    = 0;
                    for (int i = 0; i < base.DataPoints.Count; i++)
                    {
                        ChartItem chartItem = base.DataPoints[i];
                        string    s         = chartItem.Description + "(" + chartItem.Label + ")";
                        num3 += (float)font.Height + 5f;
                        float num5 = yOrigin + 5f + (float)(i - num4) * ((float)font.Height + 5f);
                        graph.DrawString(s, font, solidBrush, x, num5, stringFormat);
                        graph.FillRectangle(new SolidBrush(base.DataPoints[i].ItemColor), num2, num5 + 3f, 10f, 10f);
                    }
                    graph.DrawRectangle(pen, num, yOrigin, this._legendWidth, num3 + 5f);
                }
                finally
                {
                    font?.Dispose();
                    solidBrush?.Dispose();
                    stringFormat?.Dispose();
                    pen?.Dispose();
                }
            }
Example #10
0
            private void DrawVerticalLabelArea(Graphics graph)
            {
                Font         font          = null;
                SolidBrush   solidBrush    = null;
                StringFormat stringFormat  = null;
                Pen          pen           = null;
                StringFormat stringFormat2 = null;

                try
                {
                    font                   = new Font(this._fontFamily, 7f);
                    solidBrush             = new SolidBrush(this._fontColor);
                    stringFormat           = new StringFormat();
                    pen                    = new Pen(this._fontColor);
                    stringFormat2          = new StringFormat();
                    stringFormat.Alignment = StringAlignment.Near;
                    RectangleF layoutRectangle = new RectangleF(0f, this._yOrigin - 10f - (float)font.Height, this._xOrigin * 2f, (float)font.Height);
                    stringFormat2.Alignment = StringAlignment.Center;
                    graph.DrawString(this._yLabel, font, solidBrush, layoutRectangle, stringFormat2);
                    for (int i = 0; i < this._yTickCount; i++)
                    {
                        float      num = this._topBuffer + (float)i * this._yTickValue / this._scaleFactor;
                        float      y   = num - (float)(font.Height / 2);
                        RectangleF layoutRectangle2 = new RectangleF(5f, y, this._maxTickValueWidth, (float)font.Height);
                        graph.DrawString((this._maxValue - (float)i * this._yTickValue).ToString("#,###.##"), font, solidBrush, layoutRectangle2, stringFormat);
                        graph.DrawLine(pen, this._xOrigin, num, this._xOrigin - 4f, num);
                    }
                    graph.DrawLine(pen, this._xOrigin, this._yOrigin, this._xOrigin, this._yOrigin + this._graphHeight);
                }
                finally
                {
                    font?.Dispose();
                    solidBrush?.Dispose();
                    stringFormat?.Dispose();
                    pen?.Dispose();
                    stringFormat2?.Dispose();
                }
            }
Example #11
0
        /// <include file='doc\PrintPreviewControl.uex' path='docs/doc[@for="PrintPreviewControl.OnPaint"]/*' />
        /// <internalonly/>
        /// <devdoc>
        ///    <para>
        ///       Paints the control.
        ///    </para>
        /// </devdoc>
        protected override void OnPaint(PaintEventArgs pevent)
        {
            Brush backBrush = new SolidBrush(BackColor);

            try {
                if (pageInfo == null || pageInfo.Length == 0)
                {
                    pevent.Graphics.FillRectangle(backBrush, ClientRectangle);

                    if (pageInfo != null || exceptionPrinting)
                    {
                        // Calculate formats
                        StringFormat format = new StringFormat();
                        format.Alignment     = ControlPaint.TranslateAlignment(ContentAlignment.MiddleCenter);
                        format.LineAlignment = ControlPaint.TranslateLineAlignment(ContentAlignment.MiddleCenter);

                        // Do actual drawing
                        SolidBrush brush = new SolidBrush(ForeColor);
                        try {
                            if (exceptionPrinting)
                            {
                                pevent.Graphics.DrawString(SR.PrintPreviewExceptionPrinting, Font, brush, ClientRectangle, format);
                            }
                            else
                            {
                                pevent.Graphics.DrawString(SR.PrintPreviewNoPages, Font, brush, ClientRectangle, format);
                            }
                        }
                        finally {
                            brush.Dispose();
                            format.Dispose();
                        }
                    }
                    else
                    {
                        BeginInvoke(new MethodInvoker(CalculatePageInfo));
                    }
                }
                else
                {
                    if (!layoutOk)
                    {
                        ComputeLayout();
                    }

                    Size controlPhysicalSize = new Size(PixelsToPhysical(new Point(Size), screendpi));

                    //Point imagePixels = PhysicalToPixels(new Point(imageSize), screendpi);
                    Point virtualPixels = new Point(VirtualSize);

                    // center pages on screen if small enough
                    Point offset = new Point(Math.Max(0, (Size.Width - virtualPixels.X) / 2),
                                             Math.Max(0, (Size.Height - virtualPixels.Y) / 2));
                    offset.X  -= Position.X;
                    offset.Y  -= Position.Y;
                    lastOffset = offset;

                    int borderPixelsX = PhysicalToPixels(border, screendpi.X);
                    int borderPixelsY = PhysicalToPixels(border, screendpi.Y);

                    Region      originalClip   = pevent.Graphics.Clip;
                    Rectangle[] pageRenderArea = new Rectangle[rows * columns];
                    Point       lastImageSize  = Point.Empty;
                    int         maxImageHeight = 0;

                    try {
                        for (int row = 0; row < rows; row++)
                        {
                            //Initialize our LastImageSize variable...
                            lastImageSize.X = 0;
                            lastImageSize.Y = maxImageHeight * row;

                            for (int column = 0; column < columns; column++)
                            {
                                int imageIndex = StartPage + column + row * columns;
                                if (imageIndex < pageInfo.Length)
                                {
                                    Size pageSize = pageInfo[imageIndex].PhysicalSize;
                                    if (autoZoom)
                                    {
                                        double zoomX = ((double)controlPhysicalSize.Width - border * (columns + 1)) / (columns * pageSize.Width);
                                        double zoomY = ((double)controlPhysicalSize.Height - border * (rows + 1)) / (rows * pageSize.Height);
                                        zoom = Math.Min(zoomX, zoomY);
                                    }

                                    imageSize = new Size((int)(zoom * pageSize.Width), (int)(zoom * pageSize.Height));
                                    Point imagePixels = PhysicalToPixels(new Point(imageSize), screendpi);


                                    int x = offset.X + borderPixelsX * (column + 1) + lastImageSize.X;
                                    int y = offset.Y + borderPixelsY * (row + 1) + lastImageSize.Y;

                                    lastImageSize.X += imagePixels.X;
                                    //The Height is the Max of any PageHeight..
                                    maxImageHeight = Math.Max(maxImageHeight, imagePixels.Y);

                                    pageRenderArea[imageIndex - StartPage] = new Rectangle(x, y, imagePixels.X, imagePixels.Y);
                                    pevent.Graphics.ExcludeClip(pageRenderArea[imageIndex - StartPage]);
                                }
                            }
                        }

                        pevent.Graphics.FillRectangle(backBrush, ClientRectangle);
                    }
                    finally {
                        pevent.Graphics.Clip = originalClip;
                    }

                    for (int i = 0; i < pageRenderArea.Length; i++)
                    {
                        if (i + StartPage < pageInfo.Length)
                        {
                            Rectangle box = pageRenderArea[i];
                            pevent.Graphics.DrawRectangle(Pens.Black, box);
                            using (SolidBrush brush = new SolidBrush(ForeColor)) {
                                pevent.Graphics.FillRectangle(brush, box);
                            }
                            box.Inflate(-1, -1);
                            if (pageInfo[i + StartPage].Image != null)
                            {
                                pevent.Graphics.DrawImage(pageInfo[i + StartPage].Image, box);
                            }
                            box.Width--;
                            box.Height--;
                            pevent.Graphics.DrawRectangle(Pens.Black, box);
                        }
                    }
                }
            }
            finally {
                backBrush.Dispose();
            }

            base.OnPaint(pevent); // raise paint event
        }
Example #12
0
        /// <summary>
        /// Draws analog clock on the given GDI+ Drawing surface.
        /// </summary>
        /// <param name="e">The GDI+ Drawing surface.</param>
        private void DrawClock(Graphics e)
        {
            Graphics grfx = e;

            grfx.SmoothingMode     = smoothingMode;
            grfx.TextRenderingHint = textRenderingHint;
            grfx.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

            midx = this.ClientSize.Width / 2;
            midy = this.ClientSize.Height / 2;


            x = this.ClientSize.Width;
            y = this.ClientSize.Height;

            SolidBrush stringBrush = new SolidBrush(this.numeralColor);
            Pen        pen         = new Pen(stringBrush, 2);


            //Define rectangles inside which we will draw circles.

            Rectangle rect    = new Rectangle(0 + 10, 0 + 10, (int)x - 20, (int)y - 20);
            Rectangle rectrim = new Rectangle(0 + 20, 0 + 20, (int)x - 40, (int)y - 40);

            Rectangle rectinner      = new Rectangle(0 + 40, 0 + 40, (int)x - 80, (int)y - 80);
            Rectangle rectdropshadow = new Rectangle(0 + 10, 0 + 10, (int)x - 17, (int)y - 17);


            radius = rectinner.Width / 2;

            fontsize = radius / 5;
            textFont = this.Font;


            //Drop Shadow
            gb = new LinearGradientBrush(rect, Color.Transparent, dropShadowColor, LinearGradientMode.BackwardDiagonal);
            rectdropshadow.Offset(dropShadowOffset);
            if (this.drawDropShadow)
            {
                grfx.FillEllipse(gb, rectdropshadow);
            }


            //Face
            gb = new LinearGradientBrush(rect, rimColor1, rimColor2, faceGradientMode);
            if (this.drawRim)
            {
                grfx.FillEllipse(gb, rect);
            }



            //Rim
            gb = new LinearGradientBrush(rect, faceColor1, faceColor2, rimGradientMode);
            grfx.FillEllipse(gb, rectrim);



            //Define a circular clip region and draw the image inside it.
            GraphicsPath path = new GraphicsPath();

            path.AddEllipse(rectrim);
            grfx.SetClip(path);

            if (this.img != null)
            {
                grfx.DrawImage(this.img, rect);
            }
            path.Dispose();

            //Reset clip region
            grfx.ResetClip();

            //			Triangular region
            //			pen.Width =2;
            //			grfx.DrawRectangle(pen, rect);
            //			grfx.DrawRectangle(pen, rectinner);
            //			grfx.DrawRectangle(pen, rectrim);
            //			grfx.DrawRectangle(pen, rectdropshadow);
            //
            //			grfx.DrawRectangle(pen, rect);
            //			grfx.DrawEllipse(pen, rect);
            //			grfx.DrawEllipse(pen, rectinner);
            //			grfx.DrawEllipse(pen, rectrim);
            //			grfx.DrawEllipse(pen, rectdropshadow);
            //


            //Center Point
            //grfx.DrawEllipse(pen, midx, midy ,2 ,2);

            //Define the midpoint of the control as the centre
            grfx.TranslateTransform(midx, midy);



            StringFormat format = new StringFormat();

            format.Alignment     = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;


            //Draw Numerals on the Face
            int deg = 360 / 12;

            if (drawnumerals)
            {
                for (int i = 1; i <= 12; i++)
                {
                    grfx.DrawString(i.ToString(), textFont, stringBrush, -1 * GetX(i * deg + 90), -1 * GetY(i * deg + 90), format);
                }
            }
            format.Dispose();



            hour = time.Hour;
            min  = time.Minute;
            Point centre = new Point(0, 0);

            //Draw Minute hand
            if (drawMinuteHand)
            {
                if (minHandTickStyle == TickStyle.Smooth)
                {
                    minuteAngle = (float)(2.0 * Math.PI * (min + sec / 60.0) / 60.0);
                }
                else
                {
                    minuteAngle = (float)(2.0 * Math.PI * (min / 60.0));
                }

                pen.EndCap   = LineCap.Round;
                pen.StartCap = LineCap.RoundAnchor;
                pen.Width    = (int)radius / 14;

                centre.Offset(2, 2);
                pen.Color = Color.Gray;
                Point minHandShadow = new Point((int)(radius * Math.Sin(minuteAngle)), (int)(-(radius) * Math.Cos(minuteAngle) + 2));


                if (this.drawMinuteHandShadow)
                {
                    pen.Color = minuteHandDropShadowColor;
                    grfx.DrawLine(pen, centre, minHandShadow);
                }

                centre.X  = centre.Y = 0;
                pen.Color = minHandColor;
                Point minHand = new Point((int)(radius * Math.Sin(minuteAngle)), (int)(-(radius) * Math.Cos(minuteAngle)));
                grfx.DrawLine(pen, centre, minHand);
            }

            //--End Minute Hand


            // Draw Hour Hand
            if (drawHourHand)
            {
                hourAngle = 2.0 * Math.PI * (hour + min / 60.0) / 12.0;


                pen.EndCap   = LineCap.Round;
                pen.StartCap = LineCap.RoundAnchor;
                pen.Width    = (int)radius / 14;

                centre.X  = centre.Y = 1;
                pen.Color = Color.Gray;
                Point hourHandShadow = new Point((int)((radius * Math.Sin(hourAngle) / 1.5) + 2), (int)((-(radius) * Math.Cos(hourAngle) / 1.5) + 2));

                if (this.drawHourHandShadow)
                {
                    pen.Color = hourHandDropShadowColor;
                    grfx.DrawLine(pen, centre, hourHandShadow);
                }

                centre.X  = centre.Y = 0;
                pen.Color = hourHandColor;
                Point hourHand = new Point((int)(radius * Math.Sin(hourAngle) / 1.5), (int)(-(radius) * Math.Cos(hourAngle) / 1.5));
                grfx.DrawLine(pen, centre, hourHand);
            }
            //---End Hour Hand


            if (secondHandTickStyle == TickStyle.Smooth)
            {
                sec = time.Second + (time.Millisecond * 0.001);
            }
            else
            {
                sec = time.Second;
            }


            //Draw Sec Hand
            if (drawSecondHand)
            {
                int width = (int)radius / 25;
                pen.Width    = width;
                pen.EndCap   = secLineEndCap;
                pen.StartCap = LineCap.RoundAnchor;
                secondAngle  = 2.0 * Math.PI * sec / 60.0;



                //Draw Second Hand Drop Shadow
                pen.Color = Color.DimGray;
                centre.X  = 1;
                centre.Y  = 1;

                Point secHand       = new Point((int)(radius * Math.Sin(secondAngle)), (int)(-(radius) * Math.Cos(secondAngle)));
                Point secHandshadow = new Point((int)(radius * Math.Sin(secondAngle)), (int)(-(radius) * Math.Cos(secondAngle) + 2));



                if (drawSecondHandShadow)
                {
                    pen.Color = secondHandDropShadowColor;
                    grfx.DrawLine(pen, centre, secHandshadow);
                }

                centre.X  = centre.Y = 0;
                pen.Color = secondHandColor;
                grfx.DrawLine(pen, centre, secHand);
            }
            pen.Dispose();
        }
Example #13
0
 public void Dispose()
 {
     numberStringFormat.Dispose();
 }
Example #14
0
        private void DrawXLabelArea(Graphics graph)
        {
            Font         lblFont   = null;
            SolidBrush   brs       = null;
            StringFormat lblFormat = null;
            Pen          pen       = null;

            try
            {
                brs = new SolidBrush(_fontColor);
                pen = new Pen(_fontColor);

                if (_xTitle != null)
                {
                    lblFormat               = new StringFormat();
                    lblFormat.Alignment     = StringAlignment.Center;
                    lblFormat.LineAlignment = StringAlignment.Center;
                    //					sfVLabel.FormatFlags=StringFormatFlags.DirectionVertical;

                    lblFont = new Font(_fontFamily, _labelFontSize + 2.0f, FontStyle.Bold);
                    graph.DrawString(_xTitle, lblFont, brs, new RectangleF(_xOrigin, _yOrigin + _graphHeight + 14.0f + (_renderMode == BarGraphRenderMode.Bars?10.0f:0.0f) + ((DataPoints.Count / _interval) > 24?16.0f:0.0f), _graphWidth, 20.0f), lblFormat);
                }

                lblFont                = new Font(_fontFamily, _labelFontSize);
                lblFormat              = new StringFormat();
                lblFormat.Alignment    = StringAlignment.Center;
                lblFormat.FormatFlags |= StringFormatFlags.NoClip;
                lblFormat.Trimming     = StringTrimming.None;
                //lblFormat.FormatFlags |= StringFormatFlags.NoWrap;

                float of = 0.0f;

                if (_renderMode == BarGraphRenderMode.Bars)
                {
                    of = 10.0f;

                    // Draw x axis
                    graph.DrawLine(pen, _xOrigin + of, _yOrigin + _graphHeight + of, _xOrigin + _graphWidth + of, _yOrigin + _graphHeight + of);

                    graph.DrawLine(pen, _xOrigin, _yOrigin + _graphHeight, _xOrigin + of, _yOrigin + _graphHeight + of);
                    graph.DrawLine(pen, _xOrigin + _graphWidth, _yOrigin + _graphHeight, _xOrigin + of + _graphWidth, _yOrigin + _graphHeight + of);
                }

                float currentX;
                float currentY   = _yOrigin + _graphHeight + 2.0f;                      // All x labels are drawn 2 pixels below x-axis
                float labelWidth = _barWidth + _spaceBtwBars;                           // Fits exactly below the bar
                int   i          = 0;

                // Draw x labels
                foreach (DataItem item in DataPoints)
                {
                    if ((i % _interval) == 0)
                    {
                        currentX = _xOrigin + (i * labelWidth) + of + (labelWidth / 2);
                        RectangleF recLbl    = new RectangleF(currentX - ((labelWidth * _interval) / 2), currentY + of, labelWidth * _interval, lblFont.Height * 2);
                        string     lblString = _displayLegend ? item.Label : item.Description;                          // Decide what to show: short or long

                        graph.DrawString(lblString, lblFont, brs, recLbl, lblFormat);
                    }
                    i++;
                }
            }
            finally
            {
                if (lblFont != null)
                {
                    lblFont.Dispose();
                }
                if (brs != null)
                {
                    brs.Dispose();
                }
                if (lblFormat != null)
                {
                    lblFormat.Dispose();
                }
                if (pen != null)
                {
                    pen.Dispose();
                }
            }
        }
Example #15
0
        /// <summary>
        /// The primary purpose of trapping the Paint is to add the seperator bar - but since we're trapping the entire paint event,
        /// we need to fill in the backcolor as well
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <remarks></remarks>
        private void CollapseContainer_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
        {
            if (_palette == null)
            {
                EventArgs Ev = new EventArgs();
                OnGlobalPaletteChanged(this, Ev);
            }

            if (_PanelOpen)
            {
                _OpenHeight = this.Height;
            }
            e.Graphics.FillRectangle(new SolidBrush(this.BackColor), 0, 0, Bounds.Width, Bounds.Height);


            // Paint my background
            e.Graphics.FillRectangle(Brushes.White, 0, 0, Bounds.Width, Bounds.Height);

            // Setup our colors
            Color SepColor   = _palette.ColorTable.SeparatorDark;           //Color.FromArgb(173, 209, 255);
            Color ColorLight = _palette.ColorTable.ToolStripGradientBegin;  // Color.FromArgb(226, 238, 255);
            Color ColorDark  = _palette.ColorTable.ToolStripGradientMiddle; //Color.FromArgb(214, 232, 255);

            if (_MouseOver)
            {
                ColorDark  = ColorLight;
                ColorLight = Color.White;
            }

            Rectangle           HeaderRect  = new Rectangle(0, 0, Bounds.Width, _HeaderHeight);
            LinearGradientBrush HeaderBrush = new LinearGradientBrush(HeaderRect, Color.White, Color.White, LinearGradientMode.Horizontal);

            HeaderBrush.WrapMode = WrapMode.TileFlipX;
            HeaderBrush.SetSigmaBellShape(0.1F);

            // Set the gradient colors
            ColorBlend cb = new ColorBlend(3);

            // The Positions properties tell the gradient where to change colors
            // For this panel - our gradient is horizontal - so our positions are along the horizontal axis
            // the 1st position is 0 - the very beginning of the gradient and we should be at the 1st color
            // the 2nd position is 0.5 which means at 50% of the WIDTH of the gradient, we should be on the 2nd color
            // the 3rd position is 1.0 which means at 100% of the WIDTH of the graidne we should be on the 3rd color

            // Far left color (when horizontal) - this would be the Far Top color if Vertical
            cb.Positions[0] = 0;
            cb.Colors[0]    = ColorDark;

            // Middle color
            cb.Positions[1] = 0.5F;
            cb.Colors[1]    = ColorLight;

            // Far right color (or bottom)
            cb.Positions[2] = 1;
            cb.Colors[2]    = ColorDark;

            HeaderBrush.InterpolationColors = cb;
            e.Graphics.CompositingQuality   = CompositingQuality.HighQuality;
            e.Graphics.SmoothingMode        = SmoothingMode.HighQuality;
            e.Graphics.CompositingMode      = CompositingMode.SourceOver;
            e.Graphics.FillRectangle(HeaderBrush, HeaderRect);

            // Draw our button
            if (_Collapsable)
            {
                int ButtonY = (int)(_HeaderHeight / 2) - (imgButtons.Images[0].Height / 2);
                if (_PanelOpen)
                {
                    // Display the Up Arrows
                    e.Graphics.DrawImage(imgButtons.Images[0], Bounds.Width - 15, ButtonY);
                }
                else
                {
                    // Display the Down Arrows
                    e.Graphics.DrawImage(imgButtons.Images[1], Bounds.Width - 15, ButtonY);
                }
            }

            // Draw the borders (if not dock-filled)
            e.Graphics.DrawLine(new Pen(SepColor), 0, _HeaderHeight - 1, Bounds.Width, _HeaderHeight - 1);

            // Setup to draw the text (Font, Alignment, etc. etc.)
            Font         ActiveFont = new Font(Font.FontFamily, Font.Size, Font.Style);
            StringFormat TextFormat = new StringFormat();
            SolidBrush   FontBrush  = new SolidBrush(_palette.ColorTable.StatusStripText);

            TextFormat.FormatFlags   = StringFormatFlags.NoWrap;
            TextFormat.Trimming      = StringTrimming.EllipsisCharacter;
            TextFormat.Alignment     = StringAlignment.Near;
            TextFormat.LineAlignment = StringAlignment.Center;

            // Draw the font - but do it with style :)
            Rectangle FontBounds = new Rectangle(10, 2, Bounds.Width, _HeaderHeight - 2);

            FontBounds.X      = 10;
            FontBounds.Y      = 2;
            FontBounds.Width  = Bounds.Width;
            FontBounds.Height = _HeaderHeight - 2;

            GraphicsPath TextGraphicsPath = new GraphicsPath();

            try
            {
                //TextGraphicsPath.AddString(_HeaderText, ActiveFont.FontFamily, ActiveFont.Style, ActiveFont.Size + 3, FontBounds, TextFormat)
                //e.Graphics.SmoothingMode = SmoothingMode.HighQuality
                e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
                e.Graphics.DrawString(_HeaderText, ActiveFont, FontBrush, FontBounds, TextFormat);
                //e.Graphics.FillPath(FontBrush, TextGraphicsPath)
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            TextGraphicsPath.Dispose();
            TextGraphicsPath = null;
            ActiveFont.Dispose();
            ActiveFont = null;
            TextFormat.Dispose();
            TextFormat = null;
            //FontBounds = null;



            // Draw the bottom Seperator line (if we're not dock-filled)
            if (this.Dock != DockStyle.Fill)
            {
                e.Graphics.DrawLine(new Pen(_palette.ColorTable.SeparatorDark), 0, Bounds.Height - 1, Bounds.Width, Bounds.Height - 1);
            }
        }
Example #16
0
    private void DrawDialog(Graphics g, string title, string text)
    {
        StringFormat format = new StringFormat(StringFormatFlags.NoClip);
        format.Alignment = StringAlignment.Near;
        format.LineAlignment = StringAlignment.Center;

        Rectangle aboutRectangle = new Rectangle((Width / 2) - 90, (Height / 2) - 60, MinimumDialogHeight, 120);

        // Box
        //
        g.FillRectangle(Brushes.SteelBlue, aboutRectangle);
        g.DrawRectangle(Pens.Black, aboutRectangle);

        //Contents
        //
        aboutRectangle.Inflate(-5, -5);
        aboutRectangle.Y = aboutRectangle.Y + 5;

        Font textFont = new Font("Arial", 8f);
        //Draw text
        //
        g.DrawString(text, textFont, Brushes.White, aboutRectangle, format);

        //Title
        //
        aboutRectangle.Inflate(5, -47);
        aboutRectangle.Y = (Height / 2) - 60;
        g.FillRectangle(Brushes.Black, aboutRectangle);
        g.DrawRectangle(Pens.Black, aboutRectangle);

        aboutRectangle.Inflate(-5, 0);
        g.DrawString(title, textFont, Brushes.White, aboutRectangle, format);

        //Close
        //
        aboutRectangle.Inflate(-78, 0);
        aboutRectangle.X = (Width / 2) + 76;
        g.FillRectangle(Brushes.Red, aboutRectangle);
        g.DrawRectangle(Pens.Black, aboutRectangle);

        StringFormat closeFormat = new StringFormat(StringFormatFlags.NoClip | StringFormatFlags.DirectionVertical);
        format.Alignment = StringAlignment.Near;
        format.LineAlignment = StringAlignment.Center;

        Font closeFont = new Font("Verdana", 10.5f, FontStyle.Bold);
        aboutRectangle.Inflate(3, -1);
        g.DrawString("X",
                     closeFont,
                     Brushes.White,
                     aboutRectangle,
                     closeFormat);

        dialogCloseRectangle = aboutRectangle;
        format.Dispose();
        closeFormat.Dispose();
        textFont.Dispose();
        closeFont.Dispose();
    }
Example #17
0
        private void PaintControl(Graphics g) {
            double[] numArray1 = null;
            double[] numArray2 = null;
            Pen pen1 = null;
            Pen pen2 = null;
            Pen pen3 = null;
            SolidBrush solidBrush = null;
            StringFormat format = null;

            try {
                pen1 = new Pen(colorGrid, 1f);
                pen2 = new Pen(colorAxis, 1f);
                solidBrush = new SolidBrush(colorAxis);
                Rectangle clientRectangle = ClientRectangle;
                Color color1 = colorBg;
                g.FillRectangle(new SolidBrush(color1), clientRectangle);
                int left = clientRectangle.Left + borderLeft;
                int top = clientRectangle.Top + borderTop;
                int width = clientRectangle.Width - borderLeft - borderRight;
                int height = clientRectangle.Height - borderTop - borderBottom;
                int right = clientRectangle.Right - borderRight;
                int bottom = clientRectangle.Bottom - borderBottom;
                int xCount = 1;
                int xGridPixel = 0;
                format = new StringFormat();

                // 画x轴
                if (xLogBase < 2) {
                    xCount = Convert.ToInt32((xRangeEnd - xRangeStart) / xGrid);
                    if (xCount == 0) {
                        xCount = 1;
                    }
                    xGridPixel = width / xCount;
                    for (int i = 0; i <= xCount; ++i) {
                        int xCoor = i * xGridPixel + left;
                        g.DrawLine(pen1, xCoor, top, xCoor, bottom);
                        string str = Convert.ToString((xRangeEnd - xRangeStart) * i / xCount + xRangeStart);
                        SizeF sizeF = g.MeasureString(str, fontAxis);
                        g.DrawString(str, fontAxis, solidBrush, xCoor - sizeF.Width * 0.5f, sizeF.Height * 0.5f + bottom);
                    }
                } else {
                    xCount = Convert.ToInt32(Math.Log(xRangeEnd, xLogBase) - Math.Log(xRangeStart, xLogBase));
                    if (xCount == 0) {
                        xCount = 1;
                    }
                    xGridPixel = width / xCount;
                    for (int i = 0; i <= xCount; ++i) {
                        int xCoor = i * xGridPixel + left;
                        if (i < xCount) {
                            for (int index2 = 1; index2 < xLogBase; ++index2) {
                                int xCoorLog = xCoor + Convert.ToInt32(Math.Log(index2, xLogBase) * xGridPixel);
                                g.DrawLine(pen1, xCoorLog, top, xCoorLog, bottom);
                            }
                        }
                        string str = Convert.ToString(Math.Pow(xLogBase, Math.Log(xRangeStart, xLogBase) + i));
                        SizeF sizeF = g.MeasureString(str, fontAxis);
                        g.DrawString(str, fontAxis, solidBrush, xCoor - sizeF.Width * 0.5f, sizeF.Height * 0.5f + bottom);
                    }
                }

                // 画y轴
                int yCount = 1;
                int yGridPixel = 0;
                if (yLogBase < 2) {
                    yCount = Convert.ToInt32((yRangeEnd - yRangeStart) / yGrid);
                    if (yCount == 0) {
                        yCount = 1;
                    }
                    yGridPixel = height / yCount;
                    for (int i = 0; i <= yCount; ++i) {
                        int yCoor = bottom - i * yGridPixel;
                        g.DrawLine(pen1, left, yCoor, right, yCoor);
                        string str = Convert.ToString((yRangeEnd - yRangeStart) * i / yCount + yRangeStart);
                        SizeF sizeF = g.MeasureString(str, fontAxis);
                        g.DrawString(str, fontAxis, solidBrush, (float)(left - sizeF.Width - sizeF.Height * 0.25), yCoor - sizeF.Height * 0.5f);
                    }
                } else {
                    yCount = Convert.ToInt32(Math.Log(yRangeEnd, yLogBase) - Math.Log(yRangeStart, yLogBase));
                    if (yCount == 0) {
                        yCount = 1;
                    }
                    yGridPixel = height / yCount;
                    for (int i = 0; i <= yCount; ++i) {
                        int yCoor = bottom - i * yGridPixel;
                        if (i < yCount) {
                            for (int j = 1; j < yLogBase; ++j) {
                                int yCoorLog = yCoor - Convert.ToInt32(Math.Log(j, yLogBase) * yGridPixel);
                                g.DrawLine(pen1, left, yCoorLog, right, yCoorLog);
                            }
                        }
                        string str = Convert.ToString(Math.Pow(yLogBase, Math.Log(yRangeStart, yLogBase) + i));
                        SizeF sizeF = g.MeasureString(str, fontAxis);
                        g.DrawString(str, fontAxis, solidBrush, (float)(left - sizeF.Width - sizeF.Height * 0.25), yCoor - sizeF.Height * 0.5f);
                    }
                }

                // 画外框
                g.DrawRectangle(pen2, left, top, width, height);
                // 画x轴标签
                SizeF sizeF1 = g.MeasureString(xLabel, fontAxis);
                g.DrawString(xLabel, fontAxis, solidBrush, ((right - left) / 2 + left) - sizeF1.Width * 0.5f, sizeF1.Height * 2f + bottom);
                // 画图表名称
                RectangleF layoutRectangle = new RectangleF(0.0f, 5f, Width, 20f);
                format.Alignment = StringAlignment.Center;
                g.DrawString(strName, fontAxis, solidBrush, layoutRectangle, format);

                // 画曲线
                int xPixel = xGridPixel * xCount;
                int yPixel = yGridPixel * yCount;
                for (int i = 0; i < 5; ++i) {
                    Color color2 = new Color();
                    bool flag = false;
                    switch (i) {
                    case 0:
                        numArray1 = xData1;
                        numArray2 = yData1;
                        flag = showData1;
                        color2 = colorSet1;
                        break;
                    case 1:
                        numArray1 = xData2;
                        numArray2 = yData2;
                        flag = showData2;
                        color2 = colorSet2;
                        break;
                    case 2:
                        numArray1 = xData3;
                        numArray2 = yData3;
                        flag = showData3;
                        color2 = colorSet3;
                        break;
                    case 3:
                        numArray1 = xData4;
                        numArray2 = yData4;
                        flag = showData4;
                        color2 = colorSet4;
                        break;
                    case 4:
                        numArray1 = xData5;
                        numArray2 = yData5;
                        flag = showData5;
                        color2 = colorSet5;
                        break;
                    }
                    if (flag && numArray1 != null && (numArray2 != null && numArray1.Length == numArray2.Length)) {
                        Point[] pointArray = new Point[numArray1.Length];
                        Point point2 = new Point(left, bottom);
                        for (int j = 0; j < pointArray.Length; ++j) {
                            try {
                                if (xLogBase >= 2) {
                                    pointArray[j].X = Convert.ToInt32((Math.Log(numArray1[j], xLogBase) - Math.Log(xRangeStart, xLogBase)) / (Math.Log(xRangeEnd, xLogBase) - Math.Log(xRangeStart, xLogBase)) * xPixel + left);
                                } else {
                                    pointArray[j].X = Convert.ToInt32((numArray1[j] - xRangeStart) / (xRangeEnd - xRangeStart) * xPixel + left);
                                }
                                if (yLogBase >= 2) {
                                    pointArray[j].Y = Convert.ToInt32(bottom - (Math.Log(numArray2[j], yLogBase) - Math.Log(yRangeStart, yLogBase)) / (Math.Log(yRangeEnd, yLogBase) - Math.Log(yRangeStart, yLogBase)) * yPixel);
                                } else {
                                    pointArray[j].Y = Convert.ToInt32(bottom - (numArray2[j] - yRangeStart) / (yRangeEnd - yRangeStart) * yPixel);
                                }
                                point2 = pointArray[j];
                            } catch (Exception) {
                                pointArray[j] = point2;
                            }
                        }
                        pen3 = new Pen(color2, penWidth);
                        for (int j = 0; j < pointArray.Length; ++j) {
                            switch (drawMode) {
                            case DGChartControl.DrawModeType.Dot:
                                g.DrawEllipse(pen3, pointArray[j].X - penWidth / 2, pointArray[j].Y - penWidth / 2, penWidth, penWidth);
                                break;
                            case DGChartControl.DrawModeType.Bar:
                                g.DrawLine(pen3, new Point(pointArray[j].X, bottom), pointArray[j]);
                                break;
                            default:
                                if (j > 0) {
                                    g.DrawLine(pen3, pointArray[j - 1], pointArray[j]);
                                }
                                break;
                            }
                        }
                    }
                }
            } catch (Exception) {
                MessageBox.Show("PaintControl() in DGChartControl occurred ERROR");
            } finally {
                if (pen1 != null) {
                    pen1.Dispose();
                }
                if (pen2 != null) {
                    pen2.Dispose();
                }
                if (pen3 != null) {
                    pen3.Dispose();
                }
                if (solidBrush != null) {
                    solidBrush.Dispose();
                }
                if (format != null) {
                    format.Dispose();
                }
            }
        }
Example #18
0
        //------------------------------------------------------------------------
        public bool Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, object element)
        {
            CEntiteSnmp entite = element as CEntiteSnmp;

            if (entite != null)
            {
                CRelationEntiteSnmp_ChampCustom rel = CUtilElementAChamps.GetRelationToChamp(entite, m_wndChampCustom.ChampCustom.Id) as CRelationEntiteSnmp_ChampCustom;
                if (rel != null)
                {
                    int       nWidthChampCustom = Math.Max((cellBounds.Width * m_wndChampCustom.Size.Width) / Math.Max(Size.Width, 1), 10);
                    object    val     = rel.Valeur;
                    object    valSnmp = rel.LastSnmpValue;
                    Rectangle rct     = new Rectangle(new Point(0, 0), new Size(nWidthChampCustom, cellBounds.Height));
                    rct.Offset(cellBounds.Location);
                    Pen   pen = new Pen(Color.Black, 1);
                    Brush br  = new SolidBrush(m_wndChampCustom.BackColor);
                    graphics.FillRectangle(br, rct);
                    graphics.DrawRectangle(pen, rct);

                    br.Dispose();

                    StringFormat format = new StringFormat();
                    format.LineAlignment = StringAlignment.Center;
                    format.Alignment     = StringAlignment.Near;
                    br = new SolidBrush(m_wndChampCustom.ForeColor);
                    graphics.DrawString(val == null ? "" : val.ToString(), m_wndChampCustom.Font, br, rct, format);
                    br.Dispose();
                    string strVal1 = val != null?val.ToString() : "";

                    string strVal2 = valSnmp != null?valSnmp.ToString() : "";

                    bool bHasDif = strVal1 != strVal2 && rel.DateSynchroSnmp != null;
                    rct = cellBounds;
                    rct.Offset(nWidthChampCustom, 0);
                    rct.Size = new Size(rct.Size.Width - nWidthChampCustom, rct.Size.Height);
                    if (bHasDif)
                    {
                        rct.Size = new Size(rct.Size.Width - 16, rct.Size.Height);
                    }
                    br = new SolidBrush(m_wndValeurAutre.BackColor);
                    graphics.FillRectangle(br, rct);
                    graphics.DrawRectangle(pen, rct);
                    br.Dispose();
                    pen.Dispose();
                    br = new SolidBrush(m_wndValeurAutre.ForeColor);
                    graphics.DrawString(valSnmp == null ? "" : valSnmp.ToString(), m_wndValeurAutre.Font, br, rct, format);
                    format.Dispose();
                    br.Dispose();
                    if (bHasDif)
                    {
                        rct = new Rectangle(cellBounds.Right - 16, cellBounds.Top, 16, cellBounds.Height);
                        br  = new SolidBrush(BackColor);
                        graphics.FillRectangle(br, rct);
                        br.Dispose();
                        rct.Location = new Point(rct.Left, rct.Top + rct.Height / 2 - 8);
                        rct.Height   = 16;
                        graphics.DrawImage(Resource.alerte, rct);
                    }
                    return(false);
                }
            }
            return(true);
        }
Example #19
0
        /// <summary>
        /// Draws the default button face
        /// </summary>
        /// <param name="g">The <see cref="System.Drawing.Graphics"/> context of the canvas.</param>
        /// <param name="buttonState">A <see cref="ButtonState"/> that specifies the current state.</param>
        /// <param name="style">The <see cref="GridStyleInfo"/> object that holds cell information.</param>
        public void DrawDefaultButtonFace(Graphics g, ButtonState buttonState, GridStyleInfo style)
        {
            // Set the button style properties
            ButtonEditStyleProperties sp = new ButtonEditStyleProperties(style);

            //Button bounds
            Rectangle rect     = Bounds;
            Rectangle faceRect = Rectangle.FromLTRB(rect.Left + 1, rect.Top + 1, rect.Right - 2, rect.Bottom - 2);

            bool disabled    = !sp.ButtonEditInfo.Enabled;
            bool drawPressed = (buttonState & ButtonState.Pushed) != 0;

            //Determine the Offset
            Point ptOffset = Point.Empty;

            if (drawPressed)
            {
                ptOffset = new Point(1, 1);
            }

            // Draws the image based on ButtonEditInfo.ButtonEditType
            string resourceName;

            if (sp.ButtonEditInfo.ButtonEditType != ButtonType.None)
            {
                switch (sp.ButtonEditInfo.ButtonEditType)
                {
                case ButtonType.Browse:
                    resourceName = "Browse.bmp";
                    break;

                case ButtonType.Check:
                    resourceName = "Check.bmp";
                    break;

                case ButtonType.Down:
                    resourceName = "Down.bmp";
                    break;

                case ButtonType.Left:
                    resourceName = "Left.bmp";
                    break;

                case ButtonType.Leftend:
                    resourceName = "Leftend.bmp";
                    break;

                case ButtonType.Redo:
                    resourceName = "Redo.bmp";
                    break;

                case ButtonType.Right:
                    resourceName = "Right.bmp";
                    break;

                case ButtonType.Rightend:
                    resourceName = "Rightend.bmp";
                    break;

                case ButtonType.Undo:
                    resourceName = "Undo.bmp";
                    break;

                case ButtonType.Up:
                    resourceName = "Up.bmp";
                    break;

                default:
                    resourceName = "Browse.bmp";
                    break;
                }

                // Draws the image from ButtonEditInfo.Image
                if (sp.ButtonEditInfo.ButtonEditType == ButtonType.Image)
                {
                    if (sp.ButtonEditInfo.Image != null)
                    {
                        if (!drawPressed)
                        {
                            DrawingUtils.DrawImage(g, sp.ButtonEditInfo.Image as Image, Bounds.X + 2, Bounds.Y + 2, Bounds.Width - 4, Bounds.Height - 4);
                        }
                        else
                        {
                            DrawingUtils.DrawImage(g, sp.ButtonEditInfo.Image as Image, Bounds.X + 1, Bounds.Y + 1, Bounds.Width - 4, Bounds.Height - 4);
                        }
                    }
                    return;
                }

                string prefix     = "ButtonImages.";
                string bitmapName = prefix + resourceName;

                // Instead of using GridIconPaint you could simple use Image.Draw here
                // with an existing bitmap. GridIconPaint is convenient because it lets
                // us easily draw over existing background and replace the black color
                // in the bitmap with a different color.

                iconPainter.PaintIcon(g, Bounds, ptOffset, bitmapName, Color.Black);
                return;
            }


            // Colored button drawing
            Color hilight = SystemColors.ControlLightLight;
            Color shadow  = SystemColors.ControlDarkDark;
            Color draw    = sp.ButtonEditInfo.BackColor;

            Brush br = new SolidBrush(draw);

            // Colors the button only if the ForceBackColor is set (themes application)
            if (sp.ButtonEditInfo.ForceBackColor)
            {
                if (!disabled)
                {
                    if (!drawPressed)
                    {
                        g.FillRectangle(br, Bounds);

                        if (buttonState == ButtonState.Flat)
                        {
                            ControlPaint.DrawBorder(g, Bounds, SystemColors.ControlDark, ButtonBorderStyle.Solid);
                        }
                        else
                        {
                            GridUtil.Draw3dFrame(g, rect.Left, rect.Top, rect.Right - 1, rect.Bottom - 1, 1,
                                                 hilight, shadow);
                        }
                    }
                    else
                    {
                        g.FillRectangle(br, new Rectangle(Bounds.X + 1, Bounds.Y + 1, Bounds.Width, Bounds.Height));

                        GridUtil.Draw3dFrame(g, rect.Left - 1, rect.Top - 1, rect.Right, rect.Bottom, 1,
                                             hilight, shadow);
                        br.Dispose();
                    }
                }
            }


            // Draw the button text
            string text = sp.ButtonEditInfo.Text;

            if (text != null && text.Length > 0)
            {
                Font font = style.GdipFont;

                StringFormat format        = new StringFormat();
                bool         isRightToLeft = false;

                if (this.Grid.RightToLeft == RightToLeft.Inherit && Grid.IsRightToLeft() || style.RightToLeft == RightToLeft.Yes)
                {
                    isRightToLeft = true;
                }

                if (isRightToLeft)
                {
                    format.FormatFlags |= StringFormatFlags.DirectionRightToLeft;
                }

                format.Alignment     = StringAlignment.Center;
                format.LineAlignment = StringAlignment.Center;
                format.HotkeyPrefix  = style.HotkeyPrefix;
                format.Trimming      = style.Trimming;

                if (!style.WrapText)
                {
                    format.FormatFlags = StringFormatFlags.NoWrap;
                }

                Color textColor = Grid.PrintingMode && Grid.Model.Properties.BlackWhite ? Color.Black : sp.ButtonEditInfo.TextColor;

                if (disabled)
                {
                    DrawText(g, sp.ButtonEditInfo.Text, font, faceRect, style, textColor, true, isRightToLeft);
                }

                else
                {
                    if (!drawPressed)
                    {
                        if (buttonState == ButtonState.Flat)
                        {
                            DrawText(g, sp.ButtonEditInfo.Text, font, new Rectangle(faceRect.Left, faceRect.Top, faceRect.Width, faceRect.Height), style, textColor, false, isRightToLeft);
                        }
                        else
                        {
                            DrawText(g, sp.ButtonEditInfo.Text, font, new Rectangle(faceRect.Left + 1, faceRect.Top + 1, faceRect.Width, faceRect.Height), style, textColor, false, isRightToLeft);
                        }
                    }
                    else
                    {
                        DrawText(g, sp.ButtonEditInfo.Text, font, faceRect, style, textColor, false, isRightToLeft);
                    }
                }

                format.Dispose();
            }
        }
Example #20
0
        /// <summary>
        /// Generate captcha image with colors and random noise
        /// </summary>
        private void GenerateColorCaptcha()
        {
            Bitmap bmp = new Bitmap(m_width, m_height, PixelFormat.Format32bppArgb);

            Graphics grph = Graphics.FromImage(bmp);
            grph.SmoothingMode = SmoothingMode.AntiAlias;

            Rectangle rect = new Rectangle(0, 0, m_width, m_height);

            HatchBrush hb = new HatchBrush(HatchStyle.SmallGrid, m_cImageForeColor, m_cImageBackColor);
            GraphicsPath gPath = new GraphicsPath();
            
            float fontSize = rect.Height - 10;
            Font captchaFont = new Font("Century", fontSize, FontStyle.Bold);
            SizeF textSize = grph.MeasureString(m_SecurityCode, captchaFont);
            StringFormat strformat = new StringFormat();
            strformat.Alignment = StringAlignment.Center;
            strformat.LineAlignment = StringAlignment.Center;

            grph.FillRectangle(hb, rect);

            // generate random horizontal alpha-fading colored lines for noise
            for (int i = 0; i < 6; i++)
            {
                try
                {
                    int xPoint1 = rnd.Next(m_width);
                    int xPoint2 = rnd.Next(m_width);
                    int yPoint = rnd.Next(m_height);

                    LinearGradientBrush lgb = new LinearGradientBrush(
                        new PointF(xPoint1, yPoint),
                        new PointF(xPoint2, yPoint),
                        Color.FromArgb(125, m_horizontalColor),
                        Color.FromArgb(10, m_horizontalColor));

                    Pen pen1 = new Pen(lgb, 5);

                    grph.DrawLine(pen1, new Point(xPoint1, yPoint), new Point(xPoint2, yPoint));
                    
                    lgb.Dispose();
                    pen1.Dispose();
                }
                catch { }
            }

            // generate random vertical alpha-fading colored lines for noise
            for (int j = 0; j < 6; j++)
            {
                try
                {
                    int yPoint1 = rnd.Next(m_height);
                    int yPoint2 = rnd.Next(m_height);
                    int xPoint = rnd.Next(m_width);

                    LinearGradientBrush lgb = new LinearGradientBrush(
                        new PointF(xPoint, yPoint1),
                        new PointF(xPoint, yPoint2),
                        Color.FromArgb(125, m_verticalColor),
                        Color.FromArgb(10, m_verticalColor));

                    Pen pen1 = new Pen(lgb, 5);

                    grph.DrawLine(pen1, new Point(xPoint, yPoint1), new Point(xPoint, yPoint2));

                    lgb.Dispose();
                    pen1.Dispose();
                }
                catch { }
            }

            float wDif = textSize.Width - rect.Width;
            int k = 0;

            while(wDif > 0.0F)
            {
                k++;
                captchaFont = new Font("Century", fontSize - k, FontStyle.Bold);
                wDif = grph.MeasureString(m_SecurityCode, captchaFont).Width - rect.Width;
            }


            gPath.AddString(m_SecurityCode, captchaFont.FontFamily, (int)captchaFont.Style, captchaFont.Size, rect, strformat);
            
            PointF[] transformPoints =
			{
				new PointF(rnd.Next(m_width) / 4, rnd.Next(m_height) / 4),
				new PointF(rect.Width - rnd.Next(rect.Width) / 4, rnd.Next(rect.Height) / 4),
				new PointF(rnd.Next(rect.Width) / 4, rect.Height - rnd.Next(rect.Height) / 4),
				new PointF(rect.Width - rnd.Next(rect.Width) / 4, rect.Height - rnd.Next(rect.Height) / 4)
			};

            gPath.Warp(transformPoints, rect);

            hb = new HatchBrush(HatchStyle.Percent90, m_textForeColor, m_textBackColor);
            grph.FillPath(hb, gPath);

            // generate random beziers for noise
            Pen bezierPen = new Pen(Color.FromArgb(175, m_cImageForeColor), .5F);

            for (int i = 0; i < 10; i++)
            {
                try
                {
                    PointF[] bezierPoints =
		            {
			            new PointF(rnd.Next(m_width),rnd.Next(m_height)),
			            new PointF(rnd.Next(m_width),rnd.Next(m_height)),
			            new PointF(rnd.Next(m_width),rnd.Next(m_height)),
			            new PointF(rnd.Next(m_width),rnd.Next(m_height))
		            };

                    grph.DrawBeziers(bezierPen, bezierPoints);
                }
                catch { }
            }

            bezierPen.Dispose();
            captchaFont.Dispose();
            strformat.Dispose();
            gPath.Dispose();
            grph.Dispose();
            hb.Dispose();

            m_cImage = bmp;
        }
Example #21
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();
                }
            }
        }
Example #22
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();
                }
            }
        }
Example #23
0
        /// <summary>
        /// 文字列を描画したテクスチャを返す(メイン処理)
        /// </summary>
        /// <param name="rectDrawn">描画された領域</param>
        /// <param name="ptOrigin">描画文字列</param>
        /// <param name="drawstr">描画文字列</param>
        /// <param name="drawmode">描画モード</param>
        /// <param name="fontColor">描画色</param>
        /// <param name="edgeColor">縁取色</param>
        /// <param name="gradationTopColor">グラデーション 上側の色</param>
        /// <param name="gradationBottomColor">グラデーション 下側の色</param>
        /// <returns>描画済テクスチャ</returns>
        protected Bitmap DrawPrivateFont(string drawstr, DrawMode drawmode, Color fontColor, Color edgeColor, Color gradationTopColor, Color gradationBottomColor)
        {
            if (this._fontfamily == null || drawstr == null || drawstr == "")
            {
                // nullを返すと、その後bmp→texture処理や、textureのサイズを見て__の処理で全部例外が発生することになる。
                // それは非常に面倒なので、最小限のbitmapを返してしまう。
                // まずはこの仕様で進めますが、問題有れば(上位側からエラー検出が必要であれば)例外を出したりエラー状態であるプロパティを定義するなり検討します。
                if (drawstr != "")
                {
                    Trace.TraceWarning("DrawPrivateFont()の入力不正。最小値のbitmapを返します。");
                }
                _rectStrings = new Rectangle(0, 0, 0, 0);
                _ptOrigin    = new Point(0, 0);
                return(new Bitmap(1, 1));
            }
            bool bEdge      = ((drawmode & DrawMode.Edge) == DrawMode.Edge);
            bool bGradation = ((drawmode & DrawMode.Gradation) == DrawMode.Gradation);

            // 縁取りの縁のサイズは、とりあえずフォントの大きさの1/4とする
            //int nEdgePt = (bEdge)? _pt / 4 : 0;
            //int nEdgePt = (bEdge) ? (_pt / 3) : 0; // 縁取りが少なすぎるという意見が多かったため変更。 (AioiLight)
            int nEdgePt = (bEdge) ? (10 * _pt / CDTXMania.Skin.Font_Edge_Ratio) : 0; //SkinConfigにて設定可能に(rhimm)

            // 描画サイズを測定する
            Size stringSize = System.Windows.Forms.TextRenderer.MeasureText(drawstr, this._font, new Size(int.MaxValue, int.MaxValue),
                                                                            System.Windows.Forms.TextFormatFlags.NoPrefix |
                                                                            System.Windows.Forms.TextFormatFlags.NoPadding
                                                                            );

            stringSize.Width += 10; //2015.04.01 kairera0467 ROTTERDAM NATIONの描画サイズがうまくいかんので。

            //取得した描画サイズを基に、描画先のbitmapを作成する
            Bitmap bmp = new Bitmap(stringSize.Width + nEdgePt * 2, stringSize.Height + nEdgePt * 2);

            bmp.MakeTransparent();
            Graphics g = Graphics.FromImage(bmp);

            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            StringFormat sf = new StringFormat();

            sf.LineAlignment = StringAlignment.Far;      // 画面下部(垂直方向位置)
            sf.Alignment     = StringAlignment.Center;   // 画面中央(水平方向位置)
            sf.FormatFlags   = StringFormatFlags.NoWrap; // どんなに長くて単語の区切りが良くても改行しない (AioiLight)
            sf.Trimming      = StringTrimming.None;      // どんなに長くてもトリミングしない (AioiLight)
            // レイアウト枠
            Rectangle r = new Rectangle(0, 0, stringSize.Width + nEdgePt * 2, stringSize.Height + nEdgePt * 2);

            if (bEdge)                  // 縁取り有りの描画
            {
                // DrawPathで、ポイントサイズを使って描画するために、DPIを使って単位変換する
                // (これをしないと、単位が違うために、小さめに描画されてしまう)
                float sizeInPixels = _font.SizeInPoints * g.DpiY / 72;                  // 1 inch = 72 points

                System.Drawing.Drawing2D.GraphicsPath gp = new System.Drawing.Drawing2D.GraphicsPath();
                gp.AddString(drawstr, this._fontfamily, (int)this._font.Style, sizeInPixels, r, sf);

                // 縁取りを描画する
                Pen p = new Pen(edgeColor, nEdgePt);
                p.LineJoin = System.Drawing.Drawing2D.LineJoin.Round;
                g.DrawPath(p, gp);

                // 塗りつぶす
                Brush br;
                if (bGradation)
                {
                    br = new LinearGradientBrush(r, gradationTopColor, gradationBottomColor, LinearGradientMode.Vertical);
                }
                else
                {
                    br = new SolidBrush(fontColor);
                }
                g.FillPath(br, gp);

                if (br != null)
                {
                    br.Dispose();
                }
                br = null;
                if (p != null)
                {
                    p.Dispose();
                }
                p = null;
                if (gp != null)
                {
                    gp.Dispose();
                }
                gp = null;
            }
            else
            {
                // 縁取りなしの描画
                System.Windows.Forms.TextRenderer.DrawText(g, drawstr, _font, new Point(0, 0), fontColor);
            }
#if debug表示
            g.DrawRectangle(new Pen(Color.White, 1), new Rectangle(1, 1, stringSize.Width - 1, stringSize.Height - 1));
            g.DrawRectangle(new Pen(Color.Green, 1), new Rectangle(0, 0, bmp.Width - 1, bmp.Height - 1));
#endif
            _rectStrings = new Rectangle(0, 0, stringSize.Width, stringSize.Height);
            _ptOrigin    = new Point(nEdgePt * 2, nEdgePt * 2);


            #region [ リソースを解放する ]
            if (sf != null)
            {
                sf.Dispose();
            }
            sf = null;
            if (g != null)
            {
                g.Dispose();
            }
            g = null;
            #endregion

            return(bmp);
        }
Example #24
0
 public void Dispose()
 {
     Font?.Dispose();
     Brush?.Dispose();
     StringFormat?.Dispose();
 }
Example #25
0
        private Bitmap GenerateImageFromTextWithStyle(string text)
        {
            const bool subtitleFontBold  = false;
            bool       subtitleAlignLeft = comboBoxHAlign.SelectedIndex == 0;

            // remove styles for display text (except italic)
            text = RemoveSubStationAlphaFormatting(text);
            text = text.Replace("<b>", string.Empty);
            text = text.Replace("</b>", string.Empty);
            text = text.Replace("<B>", string.Empty);
            text = text.Replace("</B>", string.Empty);
            text = text.Replace("<u>", string.Empty);
            text = text.Replace("</u>", string.Empty);
            text = text.Replace("<U>", string.Empty);
            text = text.Replace("</U>", string.Empty);

            Font font;

            try
            {
                font = new Font(_subtitleFontName, _subtitleFontSize, FontStyle.Regular);
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
                font = new Font(FontFamily.Families[0].Name, _subtitleFontSize);
            }
            var bmp = new Bitmap(400, 200);
            var g   = Graphics.FromImage(bmp);

            SizeF textSize   = g.MeasureString("Hj!", font);
            var   lineHeight = (textSize.Height * 0.64f);

            textSize = g.MeasureString(HtmlUtil.RemoveHtmlTags(text), font);
            g.Dispose();
            bmp.Dispose();
            int sizeX = (int)(textSize.Width * 0.8) + 40;
            int sizeY = (int)(textSize.Height * 0.8) + 30;

            if (sizeX < 1)
            {
                sizeX = 1;
            }
            if (sizeY < 1)
            {
                sizeY = 1;
            }
            bmp = new Bitmap(sizeX, sizeY);
            g   = Graphics.FromImage(bmp);

            var lefts = new List <float>();

            foreach (var line in HtmlUtil.RemoveOpenCloseTags(text, HtmlUtil.TagItalic, HtmlUtil.TagFont).SplitToLines())
            {
                if (subtitleAlignLeft)
                {
                    lefts.Add(5);
                }
                else
                {
                    lefts.Add((float)(bmp.Width - g.MeasureString(line, font).Width * 0.8 + 15) / 2);
                }
            }

            g.TextRenderingHint  = TextRenderingHint.AntiAliasGridFit;
            g.SmoothingMode      = SmoothingMode.AntiAlias;
            g.CompositingQuality = CompositingQuality.HighQuality;

            var sf = new StringFormat();

            sf.Alignment     = StringAlignment.Near;
            sf.LineAlignment = StringAlignment.Near;// draw the text to a path
            var path = new GraphicsPath();

            // display italic
            var   sb       = new StringBuilder();
            int   i        = 0;
            bool  isItalic = false;
            float left     = 5;

            if (lefts.Count > 0)
            {
                left = lefts[0];
            }
            float top              = 5;
            bool  newLine          = false;
            int   lineNumber       = 0;
            float leftMargin       = left;
            bool  italicFromStart  = false;
            int   newLinePathPoint = -1;
            Color c          = _subtitleColor;
            var   colorStack = new Stack <Color>();
            var   lastText   = new StringBuilder();

            while (i < text.Length)
            {
                if (text.Substring(i).StartsWith("<font ", StringComparison.OrdinalIgnoreCase))
                {
                    float addLeft           = 0;
                    int   oldPathPointIndex = path.PointCount;
                    if (oldPathPointIndex < 0)
                    {
                        oldPathPointIndex = 0;
                    }

                    if (sb.Length > 0)
                    {
                        TextDraw.DrawText(font, sf, path, sb, isItalic, subtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                    }
                    if (path.PointCount > 0)
                    {
                        PointF[] list = (PointF[])path.PathPoints.Clone(); // avoid using very slow path.PathPoints indexer!!!
                        for (int k = oldPathPointIndex; k < list.Length; k++)
                        {
                            if (list[k].X > addLeft)
                            {
                                addLeft = list[k].X;
                            }
                        }
                    }
                    if (addLeft == 0)
                    {
                        addLeft = left + 2;
                    }
                    left = addLeft;

                    if (_borderWidth > 0)
                    {
                        g.DrawPath(new Pen(_borderColor, _borderWidth), path);
                    }
                    g.FillPath(new SolidBrush(c), path);
                    path.Reset();
                    path = new GraphicsPath();
                    sb   = new StringBuilder();

                    int endIndex = text.Substring(i).IndexOf('>');
                    if (endIndex < 0)
                    {
                        i += 9999;
                    }
                    else
                    {
                        string fontContent = text.Substring(i, endIndex);
                        if (fontContent.Contains(" color="))
                        {
                            var arr = fontContent.Substring(fontContent.IndexOf(" color=", StringComparison.Ordinal) + 7).Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                            if (arr.Length > 0)
                            {
                                string fontColor = arr[0].Trim('\'').Trim('"').Trim('\'');
                                try
                                {
                                    colorStack.Push(c); // save old color
                                    if (fontColor.StartsWith("rgb("))
                                    {
                                        arr = fontColor.Remove(0, 4).TrimEnd(')').Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                                        c   = Color.FromArgb(int.Parse(arr[0]), int.Parse(arr[1]), int.Parse(arr[2]));
                                    }
                                    else
                                    {
                                        c = ColorTranslator.FromHtml(fontColor);
                                    }
                                }
                                catch
                                {
                                    c = _subtitleColor;
                                }
                            }
                        }
                        i += endIndex;
                    }
                }
                else if (text.Substring(i).StartsWith("</font>", StringComparison.OrdinalIgnoreCase))
                {
                    if (text.Substring(i).ToLower().Replace("</font>", string.Empty).Length > 0)
                    {
                        if (lastText.EndsWith(' ') && !sb.StartsWith(' '))
                        {
                            string t = sb.ToString();
                            sb.Clear();
                            sb.Append(' ');
                            sb.Append(t);
                        }

                        float addLeft           = 0;
                        int   oldPathPointIndex = path.PointCount - 1;
                        if (oldPathPointIndex < 0)
                        {
                            oldPathPointIndex = 0;
                        }
                        if (sb.Length > 0)
                        {
                            TextDraw.DrawText(font, sf, path, sb, isItalic, subtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                        }
                        if (path.PointCount > 0)
                        {
                            PointF[] list = (PointF[])path.PathPoints.Clone(); // avoid using very slow path.PathPoints indexer!!!
                            for (int k = oldPathPointIndex; k < list.Length; k++)
                            {
                                if (list[k].X > addLeft)
                                {
                                    addLeft = list[k].X;
                                }
                            }
                        }
                        if (addLeft == 0)
                        {
                            addLeft = left + 2;
                        }
                        left = addLeft;

                        if (_borderWidth > 0)
                        {
                            g.DrawPath(new Pen(_borderColor, _borderWidth), path);
                        }
                        g.FillPath(new SolidBrush(c), path);
                        path.Reset();
                        //path = new GraphicsPath();
                        sb = new StringBuilder();
                        if (colorStack.Count > 0)
                        {
                            c = colorStack.Pop();
                        }
                    }
                    i += 6;
                }
                else if (text.Substring(i).StartsWith("<i>", StringComparison.OrdinalIgnoreCase))
                {
                    italicFromStart = i == 0;
                    if (sb.Length > 0)
                    {
                        TextDraw.DrawText(font, sf, path, sb, isItalic, subtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                    }
                    isItalic = true;
                    i       += 2;
                }
                else if (text.Substring(i).StartsWith("</i>", StringComparison.OrdinalIgnoreCase) && isItalic)
                {
                    if (lastText.EndsWith(' ') && !sb.StartsWith(' '))
                    {
                        string t = sb.ToString();
                        sb.Clear();
                        sb.Append(' ');
                        sb.Append(t);
                    }
                    TextDraw.DrawText(font, sf, path, sb, isItalic, subtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                    isItalic = false;
                    i       += 3;
                }
                else if (text.Substring(i).StartsWith(Environment.NewLine))
                {
                    TextDraw.DrawText(font, sf, path, sb, isItalic, subtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);

                    top    += lineHeight;
                    newLine = true;
                    i      += Environment.NewLine.Length - 1;
                    lineNumber++;
                    if (lineNumber < lefts.Count)
                    {
                        leftMargin = lefts[lineNumber];
                        left       = leftMargin;
                    }
                    if (isItalic)
                    {
                        italicFromStart = true;
                    }
                }
                else
                {
                    sb.Append(text[i]);
                }
                i++;
            }
            if (sb.Length > 0)
            {
                TextDraw.DrawText(font, sf, path, sb, isItalic, subtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
            }
            sf.Dispose();

            if (_borderWidth > 0)
            {
                g.DrawPath(new Pen(_borderColor, _borderWidth), path);
            }
            g.FillPath(new SolidBrush(c), path);
            g.Dispose();
            var nbmp = new NikseBitmap(bmp);

            nbmp.CropTransparentSidesAndBottom(2, true);
            return(nbmp.GetBitmap());
        }
Example #26
0
 public void Dispose()
 {
     bitmap?.Dispose();
     stringFormat?.Dispose();
     brush?.Dispose();
 }
Example #27
0
        private void DrawBars(Graphics graph)
        {
            SolidBrush   brsFont  = null;
            Font         valFont  = null;
            StringFormat sfFormat = null;

            try
            {
                brsFont            = new SolidBrush(_fontColor);
                valFont            = new Font(_fontFamily, _labelFontSize);
                sfFormat           = new StringFormat();
                sfFormat.Alignment = StringAlignment.Center;
                int i = 0;

                PointF[] linePoints = null;

                if (_renderMode == BarGraphRenderMode.Lines)
                {
                    linePoints = new PointF[DataPoints.Count];
                }

                int pointIndex = 0;

                // Draw bars and the value above each bar
                using (Pen pen = new Pen(_fontColor, 0.15f))
                {
                    using (SolidBrush whiteBrsh = new SolidBrush(Color.FromArgb(128, Color.White)))
                    {
                        foreach (DataItem item in DataPoints)
                        {
                            using (SolidBrush barBrush = new SolidBrush(item.ItemColor))
                            {
                                float itemY = _yOrigin + _graphHeight - item.SweepSize;

                                if (_renderMode == BarGraphRenderMode.Lines)
                                {
                                    linePoints[pointIndex++] = new PointF(_xOrigin + item.StartPos + (_barWidth / 2), itemY);
                                }
                                else if (_renderMode == BarGraphRenderMode.Bars)
                                {
                                    float ox = _xOrigin + item.StartPos;
                                    float oy = itemY;
                                    float ow = _barWidth;
                                    float oh = item.SweepSize;
                                    float of = 9.5f;

                                    PointF[] pts = new PointF[]
                                    {
                                        new PointF(ox, oy),
                                        new PointF(ox + ow, oy),
                                        new PointF(ox + of, oy + of),
                                        new PointF(ox + of + ow, oy + of),
                                        new PointF(ox, oy + oh),
                                        new PointF(ox + of, oy + of + oh),
                                        new PointF(ox + of + ow, oy + of + oh)
                                    };

                                    graph.FillPolygon(barBrush, new PointF[] { pts[2], pts[3], pts[6], pts[5] });

                                    using (SolidBrush ltBrsh = new SolidBrush(System.Windows.Forms.ControlPaint.Light(item.ItemColor, 0.1f)))
                                        graph.FillPolygon(ltBrsh, new PointF[] { pts[0], pts[2], pts[5], pts[4] });

                                    using (SolidBrush drkBrush = new SolidBrush(System.Windows.Forms.ControlPaint.Dark(item.ItemColor, 0.05f)))
                                        graph.FillPolygon(drkBrush, new PointF[] { pts[0], pts[1], pts[3], pts[2] });

                                    graph.DrawLine(pen, pts[0], pts[1]);
                                    graph.DrawLine(pen, pts[0], pts[2]);
                                    graph.DrawLine(pen, pts[1], pts[3]);
                                    graph.DrawLine(pen, pts[2], pts[3]);
                                    graph.DrawLine(pen, pts[2], pts[5]);
                                    graph.DrawLine(pen, pts[0], pts[4]);
                                    graph.DrawLine(pen, pts[4], pts[5]);
                                    graph.DrawLine(pen, pts[5], pts[6]);
                                    graph.DrawLine(pen, pts[3], pts[6]);

                                    // Draw data value
                                    if (_displayBarData && (i % _interval) == 0)
                                    {
                                        float      sectionWidth = (_barWidth + _spaceBtwBars);
                                        float      startX       = _xOrigin + (i * sectionWidth) + (sectionWidth / 2);                               // This draws the value on center of the bar
                                        float      startY       = itemY - 2f - valFont.Height;                                                      // Positioned on top of each bar by 2 pixels
                                        RectangleF recVal       = new RectangleF(startX - ((sectionWidth * _interval) / 2), startY, sectionWidth * _interval, valFont.Height);
                                        SizeF      sz           = graph.MeasureString(item.Value.ToString("#,###.##"), valFont, recVal.Size, sfFormat);
                                        //using ( SolidBrush brsh = new SolidBrush( Color.FromArgb( 180, 255, 255, 255 ) ) )
                                        //	graph.FillRectangle( brsh, new RectangleF(recVal.X+((recVal.Width-sz.Width)/2),recVal.Y+((recVal.Height-sz.Height)/2),sz.Width+4,sz.Height) );

                                        //graph.DrawString(item.Value.ToString("#,###.##"), valFont, brsFont, recVal, sfFormat);

                                        for (int box = -1; box <= 1; ++box)
                                        {
                                            for (int boy = -1; boy <= 1; ++boy)
                                            {
                                                if (box == 0 && boy == 0)
                                                {
                                                    continue;
                                                }

                                                RectangleF rco = new RectangleF(recVal.X + box, recVal.Y + boy, recVal.Width, recVal.Height);
                                                graph.DrawString(item.Value.ToString("#,###.##"), valFont, whiteBrsh, rco, sfFormat);
                                            }
                                        }

                                        graph.DrawString(item.Value.ToString("#,###.##"), valFont, brsFont, recVal, sfFormat);
                                    }
                                }

                                i++;
                            }
                        }

                        if (_renderMode == BarGraphRenderMode.Lines)
                        {
                            if (linePoints.Length >= 2)
                            {
                                using (Pen linePen = new Pen(Color.FromArgb(220, Color.Red), 2.5f))
                                    graph.DrawCurve(linePen, linePoints, 0.5f);
                            }

                            using (Pen linePen = new Pen(Color.FromArgb(40, _fontColor), 0.8f))
                            {
                                for (int j = 0; j < linePoints.Length; ++j)
                                {
                                    graph.DrawLine(linePen, linePoints[j], new PointF(linePoints[j].X, _yOrigin + _graphHeight));

                                    DataItem item  = DataPoints[j];
                                    float    itemY = _yOrigin + _graphHeight - item.SweepSize;

                                    // Draw data value
                                    if (_displayBarData && (j % _interval) == 0)
                                    {
                                        graph.FillEllipse(brsFont, new RectangleF(linePoints[j].X - 2.0f, linePoints[j].Y - 2.0f, 4.0f, 4.0f));

                                        float      sectionWidth = (_barWidth + _spaceBtwBars);
                                        float      startX       = _xOrigin + (j * sectionWidth) + (sectionWidth / 2);                             // This draws the value on center of the bar
                                        float      startY       = itemY - 2f - valFont.Height;                                                    // Positioned on top of each bar by 2 pixels
                                        RectangleF recVal       = new RectangleF(startX - ((sectionWidth * _interval) / 2), startY, sectionWidth * _interval, valFont.Height);
                                        SizeF      sz           = graph.MeasureString(item.Value.ToString("#,###.##"), valFont, recVal.Size, sfFormat);
                                        //using ( SolidBrush brsh = new SolidBrush( Color.FromArgb( 48, 255, 255, 255 ) ) )
                                        //	graph.FillRectangle( brsh, new RectangleF(recVal.X+((recVal.Width-sz.Width)/2),recVal.Y+((recVal.Height-sz.Height)/2),sz.Width+4,sz.Height) );

                                        for (int box = -1; box <= 1; ++box)
                                        {
                                            for (int boy = -1; boy <= 1; ++boy)
                                            {
                                                if (box == 0 && boy == 0)
                                                {
                                                    continue;
                                                }

                                                RectangleF rco = new RectangleF(recVal.X + box, recVal.Y + boy, recVal.Width, recVal.Height);
                                                graph.DrawString(item.Value.ToString("#,###.##"), valFont, whiteBrsh, rco, sfFormat);
                                            }
                                        }

                                        graph.DrawString(item.Value.ToString("#,###.##"), valFont, brsFont, recVal, sfFormat);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            finally
            {
                if (brsFont != null)
                {
                    brsFont.Dispose();
                }
                if (valFont != null)
                {
                    valFont.Dispose();
                }
                if (sfFormat != null)
                {
                    sfFormat.Dispose();
                }
            }
        }
Example #28
0
            internal static Bitmap Graphicer(string text)
            {
                string temp = text;

                while (temp.EndsWith(" ") || temp.EndsWith(" "))
                {
                    temp = temp.Remove(temp.Length - 1, 1);
                }
                if (temp == "")
                {
                    return(null);
                }
                PointF pt     = new PointF(0, pictureBox1.Height / 2);
                var    strfmt = new StringFormat {
                    Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Center
                };

                switch (Alignment)
                {
                case Alignment.Left:
                    strfmt.Alignment = StringAlignment.Near;
                    break;

                case Alignment.Center:
                    strfmt.Alignment = StringAlignment.Center;
                    pt = new PointF(pictureBox1.Width / 2, pictureBox1.Height / 2);
                    break;

                case Alignment.Right:
                    strfmt.Alignment = StringAlignment.Far;
                    pt = new PointF(pictureBox1.Width, pictureBox1.Height / 2);
                    break;
                }
                SizeF  size = new SizeF(pictureBox1.Width, pictureBox1.Height);
                Bitmap canvas;
                bool   gotsize = false;

                while (true)
                {
                    //描画先とするImageオブジェクトを作成する
                    canvas = new Bitmap((int)size.Width, pictureBox1.Height);
                    //ImageオブジェクトのGraphicsオブジェクトを作成する
                    using (var g = Graphics.FromImage(canvas))
                    {
                        using (var fnt = new Font(PrintingFont.Name, PrintingFont.Size))
                        {
                            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                            g.PixelOffsetMode   = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
                            //文字列を位置pt、黒で表示
                            g.DrawString(text, fnt, Brushes.Black, pt, strfmt);
                            if (gotsize)
                            {
                                break;
                            }
                            //画像サイズを取得
                            size = g.MeasureString(text, fnt);
                            if (size.Width == 0)
                            {
                                break;
                            }
                            gotsize = true;
                            canvas.Dispose();
                        }
                    }
                }
                strfmt.Dispose();
                return(canvas);
            }
Example #29
0
        //*********************************************************************
        //
        // This method draws the y label, tick marks, tick values, and the y axis.
        //
        //*********************************************************************

        private void DrawVerticalLabelArea(Graphics graph)
        {
            Font         lblFont   = null;
            SolidBrush   brs       = null;
            StringFormat lblFormat = null;
            Pen          pen       = null;
            StringFormat sfVLabel  = null;

            float fo = (_yTitle == null?0.0f:20.0f);

            try
            {
                brs       = new SolidBrush(_fontColor);
                lblFormat = new StringFormat();
                pen       = new Pen(_fontColor);

                if (_yTitle != null)
                {
                    sfVLabel               = new StringFormat();
                    sfVLabel.Alignment     = StringAlignment.Center;
                    sfVLabel.LineAlignment = StringAlignment.Center;
                    sfVLabel.FormatFlags   = StringFormatFlags.DirectionVertical;

                    lblFont = new Font(_fontFamily, _labelFontSize + 4.0f);
                    graph.DrawString(_yTitle, lblFont, brs, new RectangleF(0.0f, _yOrigin, 20.0f, _graphHeight), sfVLabel);
                    lblFont.Dispose();
                }

                sfVLabel               = new StringFormat();
                lblFormat.Alignment    = StringAlignment.Far;
                lblFormat.FormatFlags |= StringFormatFlags.NoClip;

                // Draw vertical label at the top of y-axis and place it in the middle top of y-axis
                lblFont = new Font(_fontFamily, _labelFontSize + 2.0f, FontStyle.Bold);
                RectangleF recVLabel = new RectangleF(0, _yOrigin - 2 * _spacer - lblFont.Height, _xOrigin * 2, lblFont.Height);
                sfVLabel.Alignment    = StringAlignment.Center;
                sfVLabel.FormatFlags |= StringFormatFlags.NoClip;
                //graph.DrawRectangle(Pens.Black,Rectangle.Truncate(recVLabel));
                graph.DrawString(_yLabel, lblFont, brs, recVLabel, sfVLabel);
                lblFont.Dispose();

                lblFont = new Font(_fontFamily, _labelFontSize);
                // Draw all tick values and tick marks
                using (Pen smallPen = new Pen(Color.FromArgb(96, _fontColor), 0.8f))
                {
                    for (int i = 0; i < _yTickCount; i++)
                    {
                        float      currentY = _topBuffer + (i * _yTickValue / _scaleFactor);                    // Position for tick mark
                        float      labelY   = currentY - lblFont.Height / 2;                                    // Place label in the middle of tick
                        RectangleF lblRec   = new RectangleF(_spacer + fo - 6, labelY, _maxTickValueWidth, lblFont.Height);

                        float currentTick = _maxValue - i * _yTickValue;                                                        // Calculate tick value from top to bottom
                        graph.DrawString(currentTick.ToString("#,###.##"), lblFont, brs, lblRec, lblFormat);                    // Draw tick value
                        graph.DrawLine(pen, _xOrigin, currentY, _xOrigin - 4.0f, currentY);                                     // Draw tick mark

                        graph.DrawLine(smallPen, _xOrigin, currentY, _xOrigin + _graphWidth, currentY);
                    }
                }

                // Draw y axis
                graph.DrawLine(pen, _xOrigin, _yOrigin, _xOrigin, _yOrigin + _graphHeight);
            }
            finally
            {
                if (lblFont != null)
                {
                    lblFont.Dispose();
                }
                if (brs != null)
                {
                    brs.Dispose();
                }
                if (lblFormat != null)
                {
                    lblFormat.Dispose();
                }
                if (pen != null)
                {
                    pen.Dispose();
                }
                if (sfVLabel != null)
                {
                    sfVLabel.Dispose();
                }
            }
        }
        private Bitmap PaintData(int width, int height)
        {
            if (width < 200)
            {
                width = 200;
            }
            if (height < 100)
            {
                height = 100;
            }

            Bitmap   bitmap = new Bitmap(width, height);
            Graphics g      = Graphics.FromImage(bitmap);

            Font         font12 = new Font("宋体", 12f);
            StringFormat sf     = new StringFormat
            {
                Alignment     = StringAlignment.Far,
                LineAlignment = StringAlignment.Center,
            };
            Pen dash = new Pen(Color.LightGray, 1f);

            dash.DashStyle   = System.Drawing.Drawing2D.DashStyle.Custom;
            dash.DashPattern = new float[] { 5, 5 };


            g.Clear(Color.White);

            if (listPaint.Count <= 5)
            {
                g.DrawString("数据太少了", font12, Brushes.DeepSkyBlue, new Rectangle(0, 0, width, height), sf);
                goto P1;
            }


            int count = (width - 60) / 6;

            TimeSpan sp           = listPaint.Max() - listPaint.Min();
            DateTime datetime_min = listPaint.Min();
            double   sep          = sp.TotalSeconds / count;

            int[] counts = new int[count];

            for (int i = 0; i < listPaint.Count; i++)
            {
                TimeSpan timeSpan = listPaint[i] - datetime_min;

                int index = (int)(timeSpan.TotalSeconds / sep);
                if (index < 0)
                {
                    index = 0;
                }
                if (index == count)
                {
                    index--;
                }
                counts[index]++;
            }

            int Max = counts.Max();
            int Min = 0;

            PaintItem[] list = new PaintItem[count];
            for (int i = 0; i < counts.Length; i++)
            {
                PaintItem item = new PaintItem();
                item.Count = counts[i];
                item.Start = listPaint[0].AddSeconds(i * sep);
                if (i == counts.Length - 1)
                {
                    item.End = listPaint[listPaint.Count - 1];
                }
                else
                {
                    item.End = listPaint[0].AddSeconds((i + 1) * sep);
                }

                list[i] = item;
            }

            listRender = new List <PaintItem>(list);


            // 左边空50,右边空10,上面20,下面30
            int left  = 50;
            int right = 10;
            int up    = 20;
            int down  = 30;

            g.DrawLine(Pens.DimGray, left, up - 10, left, height - down);
            g.DrawLine(Pens.DimGray, left, height - down + 1, width - right, height - down + 1);


            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            // 绘制箭头
            BasicFramework.SoftPainting.PaintTriangle(g, Brushes.DimGray, new Point(left, up - 10), 5, BasicFramework.GraphDirection.Upward);
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;

            int degree = 8;

            if (height < 500)
            {
                if (Max < 15 && Max > 1)
                {
                    degree = Max;
                }
            }
            else if (height < 700)
            {
                if (Max < 25 && Max > 1)
                {
                    degree = Max;
                }
                else
                {
                    degree = 16;
                }
            }
            else
            {
                if (Max < 40 && Max > 1)
                {
                    degree = Max;
                }
                else
                {
                    degree = 24;
                }
            }

            // 绘制刻度
            BasicFramework.SoftPainting.PaintCoordinateDivide(g, Pens.DimGray, dash, font12, Brushes.DimGray,
                                                              sf, degree, Max, Min, width, height, left, right, up, down);

            sf.Alignment = StringAlignment.Center;
            // 绘制总数
            g.DrawString("Totle: " + listPaint.Count, font12, Brushes.DodgerBlue,
                         new RectangleF(left, 0, width - left - right, up), sf);


            int paint_x = left + 2;

            for (int i = 0; i < list.Length; i++)
            {
                // 计算绘制位置
                float      location   = BasicFramework.SoftPainting.ComputePaintLocationY(Max, Min, height - up - down, list[i].Count) + up;
                RectangleF rectangleF = new RectangleF(paint_x, location, 5, height - down - location);
                if (rectangleF.Height <= 0 && list[i].Count > 0)
                {
                    rectangleF = new RectangleF(paint_x, height - down - 1, 5, 1);
                }
                g.FillRectangle(Brushes.Tomato, rectangleF);
                paint_x += 6;
            }

            g.DrawLine(Pens.DimGray, paint_x, up - 10, paint_x, height - down);
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            BasicFramework.SoftPainting.PaintTriangle(g, Brushes.DimGray, new Point(paint_x, up - 10), 5, BasicFramework.GraphDirection.Upward);
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;

P1:
            sf.Dispose();
            font12.Dispose();
            dash.Dispose();
            g.Dispose();
            return(bitmap);
        }
Example #31
0
        internal void Draw(Graphics e, DateItem queryInfo)
        {
            StringFormat   dateAlign    = new StringFormat();
            StringFormat   textAlign    = new StringFormat();
            Font           boldFont     = new Font(m_month.DateFont.Name, m_month.DateFont.Size, m_month.DateFont.Style | FontStyle.Bold);
            Color          bgColor1     = m_month.Colors.Days.BackColor1;
            Color          bgColor2     = m_month.Colors.Days.BackColor2;
            mcGradientMode gradientMode = m_month.Colors.Days.GradientMode;
            Color          textColor    = m_month.Colors.Days.Text;
            Color          dateColor    = m_month.Colors.Days.Date;
            Brush          dateBrush    = new SolidBrush(dateColor);
            Brush          textBrush    = new SolidBrush(textColor);
            Brush          bgBrush      = new SolidBrush(bgColor1);

            string dateString;

            m_imageRect = new Rectangle();
            string text    = "";
            bool   drawDay = false;
            bool   enabled = true;
            Image  bgImage = null;

            int i = -1;

            bool boldedDate = false;

            DateItem[] info;
            m_dayImage = null;

            dateAlign = GetStringAlignment(m_month.DateAlign);
            textAlign = GetStringAlignment(m_month.TextAlign);

            if ((m_month.SelectedMonth.Month == m_date.Month) || (m_month.Calendar.ShowTrailingDates))
            {
                drawDay = true;
            }

            if (((m_date.DayOfWeek == DayOfWeek.Saturday) && (m_month.Colors.Weekend.Saturday)) ||
                ((m_date.DayOfWeek == DayOfWeek.Sunday) && (m_month.Colors.Weekend.Sunday)))
            {
                bgColor1     = m_month.Colors.Weekend.BackColor1;
                bgColor2     = m_month.Colors.Weekend.BackColor2;
                dateColor    = m_month.Colors.Weekend.Date;
                textColor    = m_month.Colors.Weekend.Text;
                gradientMode = m_month.Colors.Weekend.GradientMode;
            }

            if (m_month.SelectedMonth.Month != m_date.Month)
            {
                bgColor1     = m_month.Colors.Trailing.BackColor1;
                bgColor2     = m_month.Colors.Trailing.BackColor2;
                gradientMode = m_month.Colors.Trailing.GradientMode;
                dateColor    = m_month.Colors.Trailing.Date;
                textColor    = m_month.Colors.Trailing.Text;
            }

            // Check if formatting should be applied
            if ((m_month.FormatTrailing) || (m_month.SelectedMonth.Month == m_date.Month))
            {
                // check of there is formatting for this day
                if (queryInfo != null)
                {
                    info    = new DateItem[1];
                    info[0] = queryInfo;
                }
                else
                {
                    info = m_calendar.GetDateInfo(this.Date);
                }
                if (info.Length > 0)
                {
                    i = 0;
                }
                // go through the available dateitems
                while ((i < info.Length) && (drawDay))
                {
                    if (info.Length > 0)
                    {
                        DateItem dateInfo = info[i];

                        if (dateInfo.BackColor1 != Color.Empty)
                        {
                            bgColor1 = dateInfo.BackColor1;
                        }
                        if (dateInfo.BackColor2 != Color.Empty)
                        {
                            bgColor2 = dateInfo.BackColor2;
                        }
                        gradientMode = dateInfo.GradientMode;
                        if (dateInfo.DateColor != Color.Empty)
                        {
                            dateColor = dateInfo.DateColor;
                        }
                        if (dateInfo.TextColor != Color.Empty)
                        {
                            textColor = dateInfo.TextColor;
                        }
                        text = dateInfo.Text;

                        if (dateInfo.Weekend)
                        {
                            bgColor1     = m_month.Colors.Weekend.BackColor1;
                            bgColor2     = m_month.Colors.Weekend.BackColor2;
                            gradientMode = m_month.Colors.Weekend.GradientMode;
                            dateColor    = m_month.Colors.Weekend.Date;
                            textColor    = m_month.Colors.Weekend.Text;
                        }
                        boldedDate = dateInfo.BoldedDate;
                        enabled    = dateInfo.Enabled;
                        if (!dateInfo.Enabled)
                        {
                            bgColor1     = m_month.Colors.Disabled.BackColor1;
                            bgColor2     = m_month.Colors.Disabled.BackColor2;
                            gradientMode = m_month.Colors.Disabled.GradientMode;
                            dateColor    = m_month.Colors.Disabled.Date;
                            textColor    = m_month.Colors.Disabled.Text;
                        }

                        m_dayImage = dateInfo.Image;

                        if (m_dayImage != null)
                        {
                            m_imageRect = ImageRect(m_month.ImageAlign);
                        }

                        bgImage = dateInfo.BackgroundImage;
                    }

                    if (m_state == mcDayState.Selected)
                    {
                        dateColor = m_month.Colors.Selected.Date;
                        textColor = m_month.Colors.Selected.Text;
                    }
                    if ((m_state == mcDayState.Focus) && (m_month.Calendar.ShowFocus))
                    {
                        dateColor = m_month.Colors.Focus.Date;
                        textColor = m_month.Colors.Focus.Text;
                    }


                    if (bgImage != null)
                    {
                        e.DrawImage(bgImage, m_rect);
                    }
                    else
                    {
                        if (gradientMode == mcGradientMode.None)
                        {
                            if (bgColor1 != Color.Transparent)
                            {
                                bgBrush = new SolidBrush(Color.FromArgb(m_month.Transparency.Background, bgColor1));
                                e.FillRectangle(bgBrush, m_rect);
                            }
                        }
                        else
                        {
                            m_calendar.DrawGradient(e, Rectangle, bgColor1, bgColor2, gradientMode);
                        }
                    }


                    ControlPaint.DrawBorder(e, m_rect, m_month.Colors.Days.Border, m_month.BorderStyles.Normal);
                    if (m_dayImage != null)
                    {
                        if (enabled)
                        {
                            e.DrawImageUnscaled(m_dayImage, m_imageRect);
                        }
                        else
                        {
                            ControlPaint.DrawImageDisabled(e, m_dayImage, m_imageRect.X, m_imageRect.Y, m_month.Colors.Disabled.BackColor1);
                        }
                    }

                    // Check if we should append month name to date
                    if ((m_month.ShowMonthInDay) &&
                        ((m_date.AddDays(-1).Month != m_date.Month) ||
                         (m_date.AddDays(1).Month != m_date.Month)))
                    {
                        dateString = m_date.Day.ToString() + " " + m_calendar.m_dateTimeFormat.GetMonthName(m_date.Month);
                    }
                    else
                    {
                        dateString = m_date.Day.ToString();
                    }

                    if (dateColor != Color.Transparent)
                    {
                        dateBrush = new SolidBrush(Color.FromArgb(m_month.Transparency.Text, dateColor));
                        CharacterRange[] characterRanges = { new CharacterRange(0, dateString.Length) };
                        dateAlign.SetMeasurableCharacterRanges(characterRanges);
                        m_dateRgn = new Region[1];
                        // Should date be bolded ?
                        if (!boldedDate)
                        {
                            e.DrawString(dateString, m_month.DateFont, dateBrush, m_rect, dateAlign);
                            m_dateRgn = e.MeasureCharacterRanges(dateString, m_month.DateFont, m_rect, dateAlign);
                        }
                        else
                        {
                            e.DrawString(dateString, boldFont, dateBrush, m_rect, dateAlign);
                            m_dateRgn = e.MeasureCharacterRanges(dateString, boldFont, m_rect, dateAlign);
                        }
                    }
                    if ((text.Length > 0) && (textColor != Color.Transparent))
                    {
                        textBrush = new SolidBrush(Color.FromArgb(m_month.Transparency.Text, textColor));
                        CharacterRange[] characterRanges = { new CharacterRange(0, text.Length) };
                        textAlign.SetMeasurableCharacterRanges(characterRanges);
                        m_textRgn = new Region[1];
                        e.DrawString(text, m_month.TextFont, textBrush, m_rect, textAlign);
                        m_textRgn = e.MeasureCharacterRanges(text, m_month.TextFont, m_rect, textAlign);
                    }
                    i++;
                }
            }

            dateBrush.Dispose();
            bgBrush.Dispose();
            textBrush.Dispose();
            boldFont.Dispose();
            dateAlign.Dispose();
            textAlign.Dispose();
        }
Example #32
0
 public void Dispose()
 {
     brush.Dispose();
     sf.Dispose();
 }
		public static Bitmap GetTextBitmap(string Text, Color BackColor, Color ForeColor, Color OutlineColor, Shape BorderShape, int Height, int Width)
		{
			Bitmap BMP = new Bitmap(1, 1);
			Graphics g = Graphics.FromImage(BMP);
			if (Width == -1 || Height == -1)
			{
				SizeF CalculatedAutoSize;
				CalculatedAutoSize = g.MeasureString(Text, Control.DefaultFont);
				if (Width == -1)
					Width = (int)(CalculatedAutoSize.Width + 3);
				if (Height == -1)
					Height = (int)(CalculatedAutoSize.Height + 1);
			}

			BMP = new Bitmap(Width, Height);
			g = Graphics.FromImage(BMP);
			g.Clear(Color.Transparent);
			Rectangle R = new Rectangle(0, 0, Width - 1, Height - 1);
			System.Drawing.SolidBrush BackColorBrush = new System.Drawing.SolidBrush(BackColor);
			System.Drawing.Pen ForeColorPen = new System.Drawing.Pen(ForeColor);
			System.Drawing.Pen OutlineColorPen = new System.Drawing.Pen(OutlineColor);
			switch (BorderShape)
			{
				case Shape.Ellipse:
					g.FillEllipse(BackColorBrush, R);
					g.DrawEllipse(OutlineColorPen, R);
					break;
				case Shape.Rectangle:
					g.FillRectangle(BackColorBrush, R);
					g.DrawRectangle(OutlineColorPen, R);
					break;
			}

			StringFormat SF = new StringFormat(StringFormatFlags.NoWrap);

			SF.Alignment = StringAlignment.Center;
			SF.LineAlignment = StringAlignment.Center;
			SF.Trimming = StringTrimming.None;

			System.Drawing.SolidBrush ForeColorBrush = new System.Drawing.SolidBrush(ForeColor);

			RectangleF RF = new RectangleF(0, 0, Width, Height);

			g.DrawString(Text, Control.DefaultFont, ForeColorBrush, RF, SF);
			SF.Dispose();
			ForeColorBrush.Dispose();
			BackColorBrush.Dispose();
			ForeColorPen.Dispose();
			OutlineColorPen.Dispose();
			g.Dispose();
			return BMP;
		}