Exemple #1
0
        public override void Paint(Graphics g, IPaintContext paintContext)
        {
            System.Drawing.Drawing2D.GraphicsState gs = g.Save();
            TransformGraphics(g);

            // Modification of StringFormat is necessary to avoid
            // too big spaces between successive words
            var strfmt = (StringFormat)StringFormat.GenericTypographic.Clone();

            strfmt.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces;

            strfmt.LineAlignment = StringAlignment.Near;
            strfmt.Alignment     = StringAlignment.Near;

            // next statement is necessary to have a consistent string length both
            // on 0 degree rotated text and rotated text
            // without this statement, the text is fitted to the pixel grid, which
            // leads to "steps" during scaling
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

            if (AutoSize)
            {
                var mySize = g.MeasureString(_text, GdiFontManager.ToGdi(_font));
                Width  = mySize.Width;
                Height = mySize.Height;
                g.DrawString(_text, GdiFontManager.ToGdi(_font), new SolidBrush(_color), 0, 0, strfmt);
            }
            else
            {
                var rect = new RectangleF(0, 0, (float)Width, (float)Height);
                g.DrawString(_text, GdiFontManager.ToGdi(_font), new SolidBrush(_color), rect, strfmt);
            }

            g.Restore(gs);
        }
 internal void ResetGraphics()
 {
     if ((this.graphics != null) && (this.savedGraphicsState != null))
     {
         this.graphics.Restore(this.savedGraphicsState);
         this.savedGraphicsState = null;
     }
 }
 protected override void Render(System.Drawing.Graphics gfx)
 {
     base.Render(gfx);
     System.Drawing.Drawing2D.GraphicsState graph = gfx.Save();
     if (RowImage != null)
     {
         gfx.DrawImage(RowImage, this.Labels[0].OffsetX - 20, 2, 17.5f, 17.5f);
         gfx.Restore(graph);
     }
 }
 protected override void Render(System.Drawing.Graphics gfx)
 {
     base.Render(gfx);
     System.Drawing.Drawing2D.GraphicsState graph = gfx.Save();
     if (TitleImage != null)
     {
         gfx.DrawImage(TitleImage, (this.PinPoint.X - 25) + (this.Size.Width - this.PinPoint.X), 5, 17.5f, 17.5f);
     }
     gfx.Restore(graph);
 }
Exemple #5
0
 protected override void Render(System.Drawing.Graphics gfx)
 {
     base.Render(gfx);
     System.Drawing.Drawing2D.GraphicsState graph = gfx.Save();
     if (TextImage != null && DrawImage)
     {
         gfx.DrawImage(TextImage, ImageOffsetX, ImageOffsetY, 17.5f, 17.5f);
         gfx.Restore(graph);
     }
 }
        public static void DrawRoundRectangleShaded(Graphics g, Size size, double r, int indent, Pen linePen, Pen penShade, int shadeSize)
        {
            //draw rounded rectangle
            int ri = DrawRoundRectangle(g, size, r, indent, linePen, penShade);

            //draw shade line
            System.Drawing.Drawing2D.GraphicsState gt = g.Save();
            g.TranslateTransform((float)(size.Width - indent + 1), (float)(size.Height - indent + 1));
            g.DrawArc(penShade, new Rectangle(-ri, -ri, ri, ri), 0, 90);
            g.Restore(gt);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="g">Graphics</param>
        /// <param name="size">size of rectangle</param>
        /// <param name="r">corner size, for example, 100</param>
        /// <param name="indent">line indent, for example, 4</param>
        /// <param name="linePen">pen to draw line, for example, Pens.Blue</param>
        /// <param name="penShade">pen to draw shade line, for example, Pen(Brushes.Gray, 2)</param>
        /// <param name="drawShadeLine">true: draw shade</param>
        public static int DrawRoundRectangle(Graphics g, Size size, double r, int indent, Pen linePen, Pen penFill)        //, bool drawShadeLine)
        {
            double w2 = (double)size.Width / (double)2;
            double h2 = (double)size.Height / (double)2;

            if (r > w2)
            {
                r = w2;
            }
            if (r > h2)
            {
                r = h2;
            }
            int ri = (int)r;
            int r2 = (int)(r / (double)2);

            System.Drawing.Drawing2D.GraphicsState gt = g.Save();
            g.TranslateTransform((float)(r), (float)(r));
            g.DrawArc(linePen, new Rectangle(-ri, -ri, ri, ri), 180, 90);
            g.Restore(gt);
            //
            g.DrawLine(linePen, r2, 0, size.Width - r2 - indent, 0);
            //
            gt = g.Save();
            g.TranslateTransform((float)(size.Width - indent), (float)(r));
            g.DrawArc(linePen, new Rectangle(-ri, -ri, ri, ri), 270, 90);
            g.Restore(gt);
            //
            g.DrawLine(linePen, size.Width - indent, r2, size.Width - indent, size.Height - r2 - indent);
            //
            g.DrawLine(penFill, size.Width - indent + 2, r2, size.Width - indent + 2, size.Height - r2 - indent + 2);
            //
            gt = g.Save();
            g.TranslateTransform((float)(r), (float)(size.Height - indent));
            g.DrawArc(linePen, new Rectangle(-ri, -ri, ri, ri), 90, 90);
            g.Restore(gt);
            //
            g.DrawLine(linePen, r2, size.Height - indent, size.Width - r2 - indent, size.Height - indent);
            //
            g.DrawLine(penFill, r2, size.Height - indent + 2, size.Width - r2 - indent + 2, size.Height - indent + 2);
            //
            gt = g.Save();
            g.TranslateTransform((float)(size.Width - indent), (float)(size.Height - indent));
            g.DrawArc(linePen, new Rectangle(-ri, -ri, ri, ri), 0, 90);
            g.Restore(gt);
            //
            g.DrawLine(linePen, 0, r2, 0, size.Height - r2 - indent);
            return(ri);
        }
 public CanvasState(GraphicsState state, FontFamily family, string font, double lineWidth, double miterLimit,
                    string lineJoin, string lineCap, string globalCompositeOperation, double shadowOffsetX,
                    double shadowOffsetY, double shadowBlur, string shadowColor, string fillStyle,
                    string strokeStyle, Matrix transformation)
 {
     _graphicsState = state;
     _family = family;
     _font = font;
     _lineWidth = lineWidth;
     _miterLimit = miterLimit;
     _lineJoin = lineJoin;
     _lineCap = lineCap;
     _globalCompositeOperation = globalCompositeOperation;
     _shadowOffsetX = shadowOffsetX;
     _shadowOffsetY = shadowOffsetY;
     _shadowBlur = shadowBlur;
     _shadowColor = shadowColor;
     _fillStyle = fillStyle;
     _strokeStyle = strokeStyle;
     Transformation = transformation;
 }
Exemple #9
0
        /// <summary>
        /// 直接绘制
        /// </summary>
        /// <param name="ca"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        public override void DirectDraw(Canvas ca, float x, float y, float dpiZoom)
        {
            SetBorder();
            MoveX = x;
            MoveY = y;
            Graphics g = ca.Graphics;

            SizeF textSize = SizeF.Empty;

            if (null != RealText)
            {
                textSize = g.MeasureString(RealText, this.Font);
            }
            float left = x;
            float top  = y;

            if (AutoSize)
            {
                this.Width  = (int)textSize.Width;
                this.Height = (int)textSize.Height;
            }

            // 上面的计算可能会改变控件的大小,所以将
            // 边框的绘制放在放在这里
            if (null != Border)
            {
                Border.FillAreaBackground(g, x, y);
                Border.DirectDraw(ca, x, y, dpiZoom);
                left += Border.BorderWidth;
                top  += Border.BorderWidth;
            }
            Brush foreBrush  = new SolidBrush(this.ForeColor);
            float tempWidth  = this.Width - Border.BorderWidth;
            float tempHeight = this.Height - Border.BorderWidth;

            if (null != RealText && tempWidth != 0 && tempHeight != 0)
            {
                StringFormat sf = GetStringFormat();
                try
                {
                    //GraphicsContainer container = g.BeginContainer();

                    System.Drawing.Drawing2D.GraphicsState state = g.Save();

                    RectangleF rect = new RectangleF(left, top, tempWidth, tempHeight);

                    Matrix mx = new Matrix();

                    if (RotateDegree != 0)
                    {
                        mx.RotateAt(RotateDegree, new PointF(rect.X + rect.Width / 2, rect.Y + rect.Height / 2));
                        //mx.Translate(textSize.Height, textSize.Width / 2);
                        mx.Multiply(g.Transform, MatrixOrder.Append);
                        g.Transform = mx;
                    }

                    g.DrawString(RealText, this.Font, foreBrush, rect /*new RectangleF(0, 0, tempWidth, tempHeight)*/, sf);
                    mx.Reset();
                    mx.Dispose();

                    g.Restore(state);
                    //g.EndContainer(container);
                }
                finally
                {
                    sf.Dispose();
                }
            }
            foreBrush.Dispose();
        }
        /// <include file='doc\Graphics.uex' path='docs/doc[@for="Graphics.Restore"]/*' />
        /// <devdoc>
        /// </devdoc>
        public void Restore(GraphicsState gstate) {
            int status = SafeNativeMethods.Gdip.GdipRestoreGraphics(new HandleRef(this, this.NativeGraphics), gstate.nativeState);

            if (status != SafeNativeMethods.Gdip.Ok) {
                throw SafeNativeMethods.Gdip.StatusException(status);
            }

            PopContext(gstate.nativeState);
        }
Exemple #11
0
 internal GraphicsContainer(GraphicsState stateObject)
 {
     _stateObject = stateObject;
 }
Exemple #12
0
 public void Restore(GraphicsState gstate)
 {
     throw new NotImplementedException();
 }
		GraphicsState Save(Matrix matrix, bool resetState) {
			GraphicsState graphicsState = new GraphicsState(this, matrix, resetState);

			PushGraphicsState( graphicsState );
			return graphicsState;
		}
Exemple #14
0
		public GraphicsState Save ()
		{						
			uint saveState;
			Status status = GDIPlus.GdipSaveGraphics (nativeObject, out saveState);
			GDIPlus.CheckStatus (status);

			GraphicsState state = new GraphicsState ();
			state.nativeState = saveState;
			return state;
		}
 public GraphicsStateRestorer(Graphics graphics, GraphicsState graphicsState)
 {
     this.graphics = graphics;
     this.graphicsState = graphicsState;
 }
 /// <summary>
 /// Sets up the transform for each shape
 /// </summary>
 /// <remarks>
 /// As each shape is drawn the transform for that shape including rotation and location is made to a new Matrix object.
 /// This matrix is used to modify the graphics transform <i>For each shape</i> 
 /// </remarks>
 /// <param name="g">The Graphics being drawn on</param>
 protected void SetupTransform(Graphics g)
 {
     state = g.Save();
     var matrix = new Matrix();
     matrix.Rotate(Rotation, MatrixOrder.Append);
     matrix.Translate(Location.X, Location.Y, MatrixOrder.Append);
     g.Transform = matrix;
 }
Exemple #17
0
        /// Some GraphPort control things
        /// 

        public virtual void SaveState()
        {
            fSavedState = fDeviceContext.Save();
        }
Exemple #18
0
        private void DrawUpcaBarcode(Graphics g, Point pt)
        {
            float width  = this.Width * this.Scale;
            float height = this.Height * this.Scale;

            // A UPCE Barcode should be a total of 71 modules wide.
            float lineWidth = width / 87f;

            // Save the GraphicsState.
            System.Drawing.Drawing2D.GraphicsState gs = g.Save();

            // Set the PageUnit to Inch because all of our measurements are in inches.
            g.PageUnit = System.Drawing.GraphicsUnit.Inch;

            // Set the PageScale to 1, so an inch will represent a true inch.
            g.PageScale = 1;

            System.Drawing.SolidBrush brush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);

            float xPosition = 0;

            System.Text.StringBuilder strbUPC = new System.Text.StringBuilder();

            float xStart = pt.X;
            float yStart = pt.Y;
            float xEnd   = 0;

            System.Drawing.Font font = new System.Drawing.Font("Arial", this.FontSize * this.Scale);

            string strEAN = string.Concat(QuiteZone, LeadTail, DigitToPatterns(data.Substring(0, data.Length / 2), _aOddParity),
                                          Separator, DigitToPatterns(data.Substring(data.Length / 2), _aEvenParity), LeadTail, QuiteZone);

            string sTempUPC = strEAN;

            float fTextHeight = g.MeasureString(sTempUPC, font).Height;

            // Draw the barcode lines.
            for (int i = 0; i < strEAN.Length; i++)
            {
                if (sTempUPC.Substring(i, 1) == "1")
                {
                    if (xStart == pt.X)
                    {
                        xStart = xPosition;
                    }

                    // Save room for the UPC number below the bar code.
                    if ((i > 12 && i < 41) | (i > 45 && i < 74))
                    {
                        // Draw space for the number
                        g.FillRectangle(brush, xPosition, yStart, lineWidth, height - fTextHeight);
                    }
                    else
                    {
                        // Draw a full line.
                        g.FillRectangle(brush, xPosition, yStart, lineWidth, height);
                    }
                }

                xPosition += lineWidth;
                xEnd       = xPosition;
            }

            g.SmoothingMode      = SmoothingMode.HighQuality;
            g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode    = PixelOffsetMode.HighQuality;
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.TextRenderingHint  = TextRenderingHint.AntiAliasGridFit;

            xPosition = xStart - g.MeasureString(string.Empty, font).Width;
            float yPosition = yStart + (height - fTextHeight);

            // Draw Product Type.
            g.DrawString(string.Empty, font, brush, new System.Drawing.PointF(xPosition, yPosition));

            // Each digit is 7 modules wide, therefore the MFG_Number is 4 digits wide so
            //    4 * 7 = 28, then add 3 for the LeadTrailer Info and another 7 for good measure,
            //    that is where the 38 comes from.
            xPosition += g.MeasureString(string.Empty, font).Width + 31 * lineWidth -
                         g.MeasureString(data.Substring(0, data.Length / 2), font).Width;

            // Draw MFG Number.
            g.DrawString(data.Substring(0, data.Length / 2), font, brush, new System.Drawing.PointF(xPosition, yPosition));

            // Add the width of the MFG Number and 5 modules for the separator.
            xPosition += g.MeasureString(data.Substring(0, data.Length / 2), font).Width +
                         5 * lineWidth;

            // Draw Product ID.
            g.DrawString(data.Substring(data.Length / 2), font, brush, new System.Drawing.PointF(xPosition, yPosition));

            // Each digit is 7 modules wide, therefore the Product Id is 5 digits wide so
            //    5 * 7 = 35, then add 3 for the LeadTrailer Info, + 8 more just for spacing
            //  that is where the 46 comes from.
            //    xPosition += 46 * lineWidth;

            // Draw Check Digit.
            //   g.DrawString(this.ChecksumDigit, font, brush, new System.Drawing.PointF(xPosition, yPosition));

            // Restore the GraphicsState.
            g.Restore(gs);
        }
Exemple #19
0
		internal GraphicsContainer (GraphicsState stateObject)
		{
			_stateObject = stateObject;
		}
 public void Restore(GraphicsState graphicsState)
 {
     this.baseGraphics.Restore(graphicsState);
 }
 public static void Save(Graphics gfx)
 {
     _gfxState = gfx.Save();
 }
Exemple #22
0
 /// <summary>
 /// Not implemented, because SvgGdi does not try and emulate GDI+ regions.
 /// </summary>
 public void Restore(GraphicsState gstate)
 {
     throw new SvgGdiNotImpl("Restore (GraphicsState gstate)");
 }
	// Restore to a previous save point.
	public void Restore(GraphicsState gstate)
			{
				if(gstate != null)
				{
					lock(this)
					{
						gstate.Restore(this);
					}
				}
			}
Exemple #24
0
        public void Paint(Graphics g,
                          IPlotArea layer,
                          Processed2DPlotData pdata)
        {
            if (this._labelColumn.Document == null)
            {
                return;
            }

            if (null != _attachedPlane)
            {
                layer.UpdateCSPlaneID(_attachedPlane);
            }


            PlotRangeList rangeList = pdata.RangeList;

            PointF[] ptArray = pdata.PlotPointsInAbsoluteLayerCoordinates;
            Altaxo.Data.IReadableColumn labelColumn = this._labelColumn.Document;


            // save the graphics stat since we have to translate the origin
            System.Drawing.Drawing2D.GraphicsState gs = g.Save();

            /*
             * double bottomPosition = 0;
             * double topPosition = 0;
             * double leftPosition = 0;
             * double rightPosition = 0;
             *
             * layer.CoordinateSystem.LogicalToLayerCoordinates(0, 0, out leftPosition, out bottomPosition);
             * layer.CoordinateSystem.LogicalToLayerCoordinates(1, 1, out rightPosition, out topPosition);
             */
            double xpos = 0, ypos = 0;
            double xpre, ypre;
            double xdiff, ydiff;

            for (int r = 0; r < rangeList.Count; r++)
            {
                int lower  = rangeList[r].LowerBound;
                int upper  = rangeList[r].UpperBound;
                int offset = rangeList[r].OffsetToOriginal;
                for (int j = lower; j < upper; j++)
                {
                    string label = labelColumn[j + offset].ToString();
                    if (label == null || label == string.Empty)
                    {
                        continue;
                    }

                    xpre = ptArray[j].X;
                    ypre = ptArray[j].Y;

                    if (null != this._attachedPlane)
                    {
                        Logical3D r3d = layer.GetLogical3D(pdata, j + offset);
                        PointF    pp  = layer.CoordinateSystem.GetPointOnPlane(this._attachedPlane, r3d);
                        xpre = pp.X;
                        ypre = pp.Y;
                    }


                    xdiff = xpre - xpos;
                    ydiff = ypre - ypos;
                    xpos  = xpre;
                    ypos  = ypre;
                    g.TranslateTransform((float)xdiff, (float)ydiff);
                    if (this._rotation != 0)
                    {
                        g.RotateTransform((float)-this._rotation);
                    }
                    this.Paint(g, label);
                    if (this._rotation != 0)
                    {
                        g.RotateTransform((float)this._rotation);
                    }
                } // end for
            }

            g.Restore(gs); // Restore the graphics state
        }
Exemple #25
0
        private void DrawUpcaBarcode(Graphics g, Point pt)
        {
            float width  = this.Width * this.Scale;
            float height = this.Height * this.Scale;

            // A UPC-A excluding 2 or 5 digit supplement information
            //	should be a total of 113 modules wide. Supplement information is typically
            //	used for periodicals and books.
            float lineWidth = width / 113f;

            // Save the GraphicsState.
            System.Drawing.Drawing2D.GraphicsState gs = g.Save();

            // Set the PageUnit to Inch because all of our measurements are in inches.
            g.PageUnit = System.Drawing.GraphicsUnit.Inch;

            // Set the PageScale to 1, so an inch will represent a true inch.
            g.PageScale = 1;

            System.Drawing.SolidBrush brush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);

            float xPosition = 0;


            float xStart = pt.X;
            float yStart = pt.Y;
            float xEnd   = 0;

            System.Drawing.Font font = new System.Drawing.Font("Arial", this.FontSize * this.Scale);

            System.Text.StringBuilder sbUPC = new System.Text.StringBuilder();
            // Build the UPC Code.
            sbUPC.AppendFormat("{0}{1}{2}{3}{4}{1}{0}",
                               this.QuiteZone, this.LeadTail,
                               DigitToPatternsLeft(this.data.Substring(0, 7)),
                               this.Separator,
                               DigitToPatterns(this.data.Substring(7), this._aRight));

            string sTempUPC = sbUPC.ToString();

            float fTextHeight = g.MeasureString(sTempUPC, font).Height;

            // Draw the barcode lines.
            for (int i = 0; i < sbUPC.Length; i++)
            {
                if (sTempUPC.Substring(i, 1) == "1")
                {
                    if (xStart == pt.X)
                    {
                        xStart = xPosition;
                    }

                    // Save room for the UPC number below the bar code.
                    if ((i > 12 && i < 55) || (i > 59 && i < 101))
                    {
                        // Draw space for the number
                        g.FillRectangle(brush, xPosition, yStart, lineWidth, height - fTextHeight);
                    }
                    else
                    {
                        // Draw a full line.
                        g.FillRectangle(brush, xPosition, yStart, lineWidth, height);
                    }
                }

                xPosition += lineWidth;
                xEnd       = xPosition;
            }

            g.SmoothingMode      = SmoothingMode.HighQuality;
            g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode    = PixelOffsetMode.HighQuality;
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.TextRenderingHint  = TextRenderingHint.AntiAliasGridFit;

            // Draw the upc numbers below the line.

            xPosition = xStart - g.MeasureString(this.CountryCode.Substring(0, 1), font).Width;
            float yPosition = yStart + (height - fTextHeight);

            // Draw Product Type.
            g.DrawString(this.CountryCode.Substring(0, 1), font, brush, new System.Drawing.PointF(xPosition, yPosition));

            // Each digit is 7 modules wide, therefore the MFG_Number is 5 digits wide so
            //    5 * 7 = 35, then add 3 for the LeadTrailer Info and another 7 for good measure,
            //    that is where the 45 comes from.
            xPosition += g.MeasureString(this.CountryCode.Substring(0, 1), font).Width + 45 * lineWidth -
                         g.MeasureString(string.Concat(this.CountryCode[1], this.ManufacturerCode), font).Width;

            // Draw MFG Number.
            g.DrawString(string.Concat(this.CountryCode[1], this.ManufacturerCode), font, brush, new System.Drawing.PointF(xPosition, yPosition));

            // Add the width of the MFG Number and 5 modules for the separator.
            xPosition += g.MeasureString(string.Concat(this.CountryCode[1], this.ManufacturerCode), font).Width +
                         5 * lineWidth;

            // Draw Product ID.
            g.DrawString(string.Concat(this.ProductCode, this.ChecksumDigit), font, brush, new System.Drawing.PointF(xPosition, yPosition));

            g.Restore(gs);
        }
        public GraphicsState Save()
        {
            if (stateStack == null)
            {
                stateStack = new object[MAX_GRAPHICS_STATE_STACK];
                statePos = 0;
            }

            var gsCurrentState = new GraphicsState();
            gsCurrentState.nativeState = ++statePos;

            var currentState = new CGGraphicsState();

            currentState.lastPen = LastPen;
            currentState.lastBrush = LastBrush;
            // Make sure we clone the Matrices or we will still modify
            // them after the save as they are the same objects.  Woops!!
            currentState.model = modelMatrix.Clone();
            currentState.view = viewMatrix.Clone();
            currentState.compositingQuality = CompositingQuality;
            currentState.compositingMode = CompositingMode;
            currentState.interpolationMode = interpolationMode;
            currentState.pageScale = pageScale;
            currentState.pageUnit = graphicsUnit;
            //currentState.pixelOffsetMode = PixelOffsetMode;
            currentState.smoothingMode = smoothingMode;
            //currentState.textContrast = TextContrast;
            //currentState.textRenderingHint = TextRenderingHint;
            currentState.renderingOrigin = renderingOrigin;

            currentState.clipRegion = clipRegion;

            stateStack[gsCurrentState.nativeState] = currentState;
            return gsCurrentState;
        }
Exemple #27
0
        public void BeginTranslate(Graphics g)
        {
            savedState = g.Save();

            var point = Center;
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
            g.PageUnit = GraphicsUnit.Pixel;
            g.TranslateTransform(-WorkspaceOrigin.X + point.X / CurrentScale, -WorkspaceOrigin.Y + point.Y / CurrentScale);
            g.PageScale = CurrentScale;
        }
Exemple #28
0
		public void Restore (GraphicsState gstate)
		{			
			// the possible NRE thrown by gstate.nativeState match MS behaviour
			Status status = GDIPlus.GdipRestoreGraphics (nativeObject, gstate.nativeState);
			GDIPlus.CheckStatus (status);
		}
Exemple #29
0
 internal GraphicsStateDisposer( Graphics g )
 {
     _g = g;
     _state = _g.Save();
 }
Exemple #30
0
        public void Paint(Graphics g, IPaintContext paintContext, bool bForPreview)
        {
            //_isStructureInSync = false;
            _isMeasureInSync = false; // Change: interpret text every time in order to update plot items and \ID

            if (!_isStructureInSync)
            {
                // this.Interpret(g);
                InterpretText();

                _isStructureInSync = true;
                _isMeasureInSync   = false;
            }

            using (var fontCache = new FontCache())
            {
                if (!_isMeasureInSync)
                {
                    // this.MeasureStructure(g, obj);
                    MeasureGlyphs(g, fontCache, paintContext);

                    MeasureBackground(g, _rootNode.Width, _rootNode.Height);

                    _isMeasureInSync = true;
                }

                _cachedSymbolPositions.Clear();

                System.Drawing.Drawing2D.GraphicsState gs = g.Save();
                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

                var bounds = Bounds;

                var transformmatrix = new Matrix();
                transformmatrix.Translate((float)_location.AbsolutePivotPositionX, (float)_location.AbsolutePivotPositionY);
                transformmatrix.Rotate((float)(-Rotation));
                transformmatrix.Shear((float)Shear, 0);
                transformmatrix.Scale((float)ScaleX, (float)ScaleY);
                transformmatrix.Translate((float)bounds.X, (float)bounds.Y);

                if (!bForPreview)
                {
                    TransformGraphics(g);
                    g.TranslateTransform((float)bounds.X, (float)bounds.Y);
                }

                // first of all paint the background
                PaintBackground(g);

                var dc = new DrawContext
                {
                    FontCache              = fontCache,
                    bForPreview            = bForPreview,
                    LinkedObject           = Altaxo.Main.AbsoluteDocumentPath.GetRootNodeImplementing <HostLayer>(this),
                    transformMatrix        = transformmatrix,
                    _cachedSymbolPositions = _cachedSymbolPositions
                };
                DrawGlyphs(g, dc, _cachedTextOffset.X, _cachedTextOffset.Y);
                g.Restore(gs);
            }
        }
Exemple #31
0
 public void Dispose()
 {
     if( _g != null )
     {
         _g.Restore( _state );
         _g = null;
         _state = null;
     }
 }
Exemple #32
0
 public void Restore(GraphicsState gstate)
 {
     _g.Restore(gstate) ;
 }
		GraphicsState PopGraphicsState() {
			GraphicsState state = _nextGraphicsState;
			_nextGraphicsState = _nextGraphicsState.Next;
			return state;
		}
Exemple #34
0
        /// <summary>
        /// 绘制
        /// </summary>
        /// <param name="ca"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        public override void Print(Canvas ca, float x, float y)
        {
            SetBorder();
            MoveX = x;
            MoveY = y;
            Graphics g = ca.Graphics;

            if (null != this.Site)
            {
                if (!string.IsNullOrEmpty(Expression) && Expression.Trim().StartsWith("="))
                {
                    RealText = Expression;
                }
            }

            if (null == this.Site && EnableMapping)
            {
                string result = GetMapValue(RealText);
                if (null != result)
                {
                    RealText = result;
                }
            }
            StringFormat sf       = GetStringFormat();
            SizeF        textSize = SizeF.Empty;

            if (null != RealText)
            {
                textSize = g.MeasureString(RealText, this.Font, (int)(this.Width - Border.BorderWidth), sf);
            }
            float left = x;
            float top  = y;

            if (AutoSize)
            {
                this.Width  = (int)textSize.Width;
                this.Height = (int)textSize.Height;
            }

            // 上面的计算可能会改变控件的大小,所以将
            // 边框的绘制放在放在这里
            if (null != Border)
            {
                Border.FillAreaBackground(g, x, y);
                Border.Print(ca, x, y);
                left += Border.BorderWidth;
                top  += Border.BorderWidth;
            }
            Brush foreBrush  = new SolidBrush(this.ForeColor);
            float tempWidth  = this.Width - Border.BorderWidth;
            float tempHeight = this.Height - Border.BorderWidth;

            if (null != RealText && tempWidth != 0 && tempHeight != 0)
            {
                try
                {
                    //GraphicsContainer container = g.BeginContainer();

                    System.Drawing.Drawing2D.GraphicsState state = g.Save();

                    RectangleF rect = new RectangleF(left, top, tempWidth, tempHeight);

                    Matrix mx = new Matrix();

                    if (RotateDegree != 0)
                    {
                        mx.RotateAt(RotateDegree, new PointF(rect.X + rect.Width / 2, rect.Y + rect.Height / 2));
                        //mx.Translate((float)(Math.Sin(RotateDegree * Math.PI / 180) * textSize.Width), 0);
                        //left += (int)(textSize.Height / 2);

                        //mx.RotateAt(RotateDegree, new PointF(x, y));
                        //if (Math.Sin(RotateDegree * Math.PI / 180) < 0)
                        //    mx.Translate((float)(Math.Sin(RotateDegree * Math.PI / 180) * textSize.Width),0 /*(float)Math.Cos(RotateDegree * Math.PI / 180) * textSize.Width*/ );
                        mx.Multiply(g.Transform, MatrixOrder.Append);
                        g.Transform = mx;
                    }

                    g.DrawString(RealText, this.Font, foreBrush, rect, sf);
                    mx.Reset();
                    mx.Dispose();

                    g.Restore(state);
                    //g.EndContainer(container);
                    //g.DrawString(RealText, this.Font, foreBrush, new RectangleF(left, top, tempWidth, tempHeight), sf);
                }
                finally
                {
                    sf.Dispose();
                }
            }
            foreBrush.Dispose();
        }
Exemple #35
0
        private void DrawUpcaBarcode(Graphics g, Point pt)
        {
            float width  = this.Width * this.Scale;
            float height = this.Height * this.Scale;

            // A UPCE Barcode should be a total of 71 modules wide.
            float lineWidth = width / 71f;

            // Save the GraphicsState.
            System.Drawing.Drawing2D.GraphicsState gs = g.Save();

            // Set the PageUnit to Inch because all of our measurements are in inches.
            g.PageUnit = System.Drawing.GraphicsUnit.Inch;

            // Set the PageScale to 1, so an inch will represent a true inch.
            g.PageScale = 1;

            System.Drawing.SolidBrush brush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);

            float xPosition = 0;

            System.Text.StringBuilder strbUPC = new System.Text.StringBuilder();

            float xStart = pt.X;
            float yStart = pt.Y;
            float xEnd   = 0;

            System.Drawing.Font font = new System.Drawing.Font("Arial", this.FontSize * this.Scale);


            string pattern = (data[0] == '0') ? numberSystem_0[int.Parse(data.Substring(7, 1))]
                                : numberSystem_1[int.Parse(data.Substring(7, 1))];

            string strUPC           = QuiteZone + LeadTail;
            string ManufacturerCode = this.data.Substring(1, 6);

            for (int i = 0; i < pattern.Length; i++)
            {
                int n = int.Parse(Convert.ToString(ManufacturerCode[i]));
                if (pattern[i] == 'O')
                {
                    strUPC += _aOddParity[n];
                }
                else if (pattern[i] == 'E')
                {
                    strUPC += _aEvenParity[n];
                }
            }
            strUPC += Separator;
            strUPC += QuiteZone;

            string sTempUPC = strUPC;

            float fTextHeight = g.MeasureString(sTempUPC, font).Height;

            // Draw the barcode lines.
            for (int i = 0; i < strUPC.Length; i++)
            {
                if (sTempUPC.Substring(i, 1) == "1")
                {
                    if (xStart == pt.X)
                    {
                        xStart = xPosition;
                    }

                    // Save room for the UPC number below the bar code.
                    if ((i > 12 && i < 55))
                    {
                        // Draw space for the number
                        g.FillRectangle(brush, xPosition, yStart, lineWidth, height - fTextHeight);
                    }
                    else
                    {
                        // Draw a full line.
                        g.FillRectangle(brush, xPosition, yStart, lineWidth, height);
                    }
                }

                xPosition += lineWidth;
                xEnd       = xPosition;
            }

            g.SmoothingMode      = SmoothingMode.HighQuality;
            g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode    = PixelOffsetMode.HighQuality;
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.TextRenderingHint  = TextRenderingHint.AntiAliasGridFit;

            // Draw the upc numbers below the line.
            xPosition = xStart - g.MeasureString(this.data.Substring(0, 1), font).Width;
            float yPosition = yStart + (height - fTextHeight);

            // Draw Product Type.
            g.DrawString(this.data.Substring(0, 1), font, brush, new System.Drawing.PointF(xPosition, yPosition));

            // Each digit is 7 modules wide, therefore the MFG_Number is 5 digits wide so
            //    5 * 7 = 35, then add 3 for the LeadTrailer Info and another 7 for good measure,
            //    that is where the 45 comes from.
            xPosition += g.MeasureString(this.data.Substring(0, 1), font).Width + 38 * lineWidth -
                         g.MeasureString(ManufacturerCode, font).Width;

            // Draw MFG Number.
            g.DrawString(ManufacturerCode, font, brush, new System.Drawing.PointF(xPosition, yPosition));

            // Add the width of the MFG Number and 5 modules for the separator.
            xPosition += g.MeasureString(ManufacturerCode, font).Width +
                         13 * lineWidth;

            // Draw Product ID.
            //g.DrawString(this.ProductCode, font, brush, new System.Drawing.PointF(xPosition, yPosition));

            // Each digit is 7 modules wide, therefore the Product Id is 5 digits wide so
            //    6 * 7 = 42, then add 3 for the LeadTrailer Info and add 5 for seprator, + 8 more just for spacing
            //  that is where the 46 comes from.
            //xPosition += 58 * lineWidth;

            // Draw Check Digit.
            g.DrawString(this.data.Substring(7, 1), font, brush, new System.Drawing.PointF(xPosition, yPosition));

            // Restore the GraphicsState.
            g.Restore(gs);
        }
 internal XGraphicsContainer(GraphicsState state)
 {
   GdipState = state;
 }
 public void Restore(GraphicsState gstate)
 {
     LastPen = gstate.lastPen;
     LastBrush = gstate.lastBrush;
     modelMatrix = gstate.model;
     viewMatrix = gstate.view;
     renderingOrigin = gstate.renderingOrigin;
     graphicsUnit = gstate.pageUnit;
     pageScale = gstate.pageScale;
     SmoothingMode = gstate.smoothingMode;
     clipRegion = gstate.clipRegion;
     //applyModelView();
     // I do not know if we should use the contexts save/restore state or our own
     // we will do that save state for now
     context.RestoreState();
 }
Exemple #38
0
        /// <summary>
        /// Paints the axis style labels.
        /// </summary>
        /// <param name="g">Graphics environment.</param>
        /// <param name="coordSyst">The coordinate system. Used to get the path along the axis.</param>
        /// <param name="scale">Scale.</param>
        /// <param name="tickSpacing">If not <c>null</c>, this parameter provides a custom tick spacing that is used instead of the default tick spacing of the scale.</param>
        /// <param name="styleInfo">Information about begin of axis, end of axis.</param>
        /// <param name="outerDistance">Distance between axis and labels.</param>
        /// <param name="useMinorTicks">If true, minor ticks are shown.</param>
        public virtual void Paint(Graphics g, G2DCoordinateSystem coordSyst, Scale scale, TickSpacing tickSpacing, CSAxisInformation styleInfo, double outerDistance, bool useMinorTicks)
        {
            _cachedAxisStyleInfo = styleInfo;
            CSLineID    styleID = styleInfo.Identifier;
            Scale       raxis   = scale;
            TickSpacing ticking = tickSpacing;

            _enclosingPath.Reset();
            _enclosingPath.FillMode = FillMode.Winding; // with Winding also overlapping rectangles are selected
            var helperPath = new GraphicsPath();
            var math       = new Matrix();

            Logical3D r0 = styleID.GetLogicalPoint(styleInfo.LogicalValueAxisOrg);
            Logical3D r1 = styleID.GetLogicalPoint(styleInfo.LogicalValueAxisEnd);

            Logical3D outer;
            var       dist_x = outerDistance; // Distance from axis tick point to label
            var       dist_y = outerDistance; // y distance from axis tick point to label

            // dist_x += this._font.SizeInPoints/3; // add some space to the horizontal direction in order to separate the chars a little from the ticks

            // next statement is necessary to have a consistent string length both
            // on 0 degree rotated text and rotated text
            // without this statement, the text is fitted to the pixel grid, which
            // leads to "steps" during scaling
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

            double[]        relpositions;
            AltaxoVariant[] ticks;
            if (useMinorTicks)
            {
                relpositions = ticking.GetMinorTicksNormal(raxis);
                ticks        = ticking.GetMinorTicksAsVariant();
            }
            else
            {
                relpositions = ticking.GetMajorTicksNormal(raxis);
                ticks        = ticking.GetMajorTicksAsVariant();
            }

            if (!_suppressedLabels.IsEmpty)
            {
                var filteredTicks        = new List <AltaxoVariant>();
                var filteredRelPositions = new List <double>();

                for (int i = 0; i < ticks.Length; i++)
                {
                    if (_suppressedLabels.ByValues.Contains(ticks[i]))
                    {
                        continue;
                    }
                    if (_suppressedLabels.ByNumbers.Contains(i))
                    {
                        continue;
                    }
                    if (_suppressedLabels.ByNumbers.Contains(i - ticks.Length))
                    {
                        continue;
                    }

                    filteredTicks.Add(ticks[i]);
                    filteredRelPositions.Add(relpositions[i]);
                }
                ticks        = filteredTicks.ToArray();
                relpositions = filteredRelPositions.ToArray();
            }

            IMeasuredLabelItem[] labels = _labelFormatting.GetMeasuredItems(g, _font, _stringFormat, ticks);

            double     emSize    = _font.Size;
            CSAxisSide labelSide = null != _labelSide ? _labelSide.Value : styleInfo.PreferredLabelSide;

            for (int i = 0; i < ticks.Length; i++)
            {
                double r = relpositions[i];

                if (!Altaxo.Calc.RMath.IsInIntervalCC(r, -1000, 1000))
                {
                    continue;
                }

                outer = coordSyst.GetLogicalDirection(styleID.ParallelAxisNumber, labelSide);
                PointD2D tickorg = coordSyst.GetNormalizedDirection(r0, r1, r, outer, out var outVector);
                PointD2D tickend = tickorg + outVector * outerDistance;

                PointD2D msize = labels[i].Size;
                PointD2D morg  = tickend;

                if (_automaticRotationShift)
                {
                    double alpha = _rotation * Math.PI / 180 - Math.Atan2(outVector.Y, outVector.X);
                    double shift = msize.Y * 0.5 * Math.Abs(Math.Sin(alpha)) + (msize.X + _font.Size / 2) * 0.5 * Math.Abs(Math.Cos(alpha));
                    morg = morg + outVector * shift;
                }
                else
                {
                    morg = morg.WithXPlus(outVector.X * _font.Size / 3);
                }

                var mrect = new RectangleD2D(morg, msize);
                if (_automaticRotationShift)
                {
                    AdjustRectangle(ref mrect, StringAlignment.Center, StringAlignment.Center);
                }
                else
                {
                    AdjustRectangle(ref mrect, _horizontalAlignment, _verticalAlignment);
                }

                math.Reset();
                math.Translate((float)morg.X, (float)morg.Y);
                if (_rotation != 0)
                {
                    math.Rotate((float)-_rotation);
                }
                math.Translate((float)(mrect.X - morg.X + emSize * _xOffset), (float)(mrect.Y - morg.Y + emSize * _yOffset));

                System.Drawing.Drawing2D.GraphicsState gs = g.Save();
                g.MultiplyTransform(math);

                if (_backgroundStyle != null)
                {
                    _backgroundStyle.Draw(g, new RectangleD2D(PointD2D.Empty, msize));
                }

                _brush.SetEnvironment(new RectangleD2D(PointD2D.Empty, msize), BrushX.GetEffectiveMaximumResolution(g, 1));
                labels[i].Draw(g, _brush, new PointF(0, 0));
                g.Restore(gs); // Restore the graphics state

                helperPath.Reset();
                helperPath.AddRectangle(new RectangleF(PointF.Empty, (SizeF)msize));
                helperPath.Transform(math);

                _enclosingPath.AddPath(helperPath, true);
            }
        }
Exemple #39
0
    private void DrawMeasure(Graphics graphics, IGeometry geometry)
    {
        string measureUnits = AppSettings.MeasureUnits;
        bool   inFeet       = measureUnits == "feet" || measureUnits == "both";
        bool   inMeters     = measureUnits == "meters" || measureUnits == "both";

        System.Drawing.Font font = AppSettings.MeasureFont;
        font = new System.Drawing.Font(font.FontFamily, Convert.ToSingle(font.Size * _resolution), font.Style, font.Unit);
        SolidBrush brush     = new SolidBrush(Color.FromArgb(64, 64, 64));
        SolidBrush glowBrush = new SolidBrush(Color.White);

        StringFormat format = new StringFormat();

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

        double           convert = 1 / (AppSettings.MapUnits == "feet" ? 1 : Constants.MetersPerFoot);
        StringCollection text    = new StringCollection();

        switch (geometry.OgcGeometryType)
        {
        case OgcGeometryType.LineString:
            ILineString lineString = (ILineString)geometry;

            double d = lineString.Length * convert;

            if (inFeet)
            {
                text.Add(d < 5280 ? d.ToString("0") + " ft" : (d / 5280).ToString("0.0") + " mi");
            }

            if (inMeters)
            {
                d *= Constants.MetersPerFoot;
                text.Add(d < 1000 ? d.ToString("0") + " m" : (d / 1000).ToString("0.0") + " km");
            }

            IPoint p;
            double angle;

            GetMidpoint(lineString, out p, out angle);

            angle = -(angle * 180 / Math.PI);
            angle = angle < -90 || 90 < angle ? angle + 180 : angle < 0 ? angle + 360 : angle;

            p = _transform.ReverseTransform(p);

            float x = Convert.ToSingle(p.Coordinate.X * _resolution);
            float y = Convert.ToSingle(p.Coordinate.Y * _resolution);

            format.LineAlignment = StringAlignment.Far;

            int[] pos = new int[] { 0, 1, 2, 3, 5, 6, 7, 8, 4 };

            for (int i = 0; i < 9; ++i)
            {
                float offsetX = (pos[i] % 3) - 1;
                float offsetY = Convert.ToSingle(Math.Floor(pos[i] / 3.0)) - 1;

                System.Drawing.Drawing2D.GraphicsState state = graphics.Save();
                graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
                graphics.TranslateTransform(x, y);
                graphics.RotateTransform(Convert.ToSingle(angle));
                graphics.DrawString(text.Join("\n"), font, i < 8 ? glowBrush : brush, Convert.ToSingle(offsetX * _resolution), Convert.ToSingle(offsetY - 3 * _resolution), format);
                graphics.Restore(state);
            }
            break;

        case OgcGeometryType.Polygon:
            IPolygon polygon = (IPolygon)geometry;
            IPoint   c       = polygon.Centroid;

            if (c != null)
            {
                double a     = polygon.Area * convert * convert;
                double acres = a / Constants.SquareFeetPerAcre;

                if (inFeet)
                {
                    double squareMile = Constants.FeetPerMile * Constants.FeetPerMile;
                    text.Add(a <= squareMile ? a.ToString("0") + " sq ft" : (a / squareMile).ToString("0.00") + " sq mi");
                }

                if (inMeters)
                {
                    a *= Constants.MetersPerFoot * Constants.MetersPerFoot;
                    text.Add(a <= 100000 ? a.ToString("0") + " sq m" : (a / 1000000).ToString("0.00") + " sq km");
                }

                if (inFeet)
                {
                    text.Add(acres.ToString("0.00") + " acres");
                }

                DrawText(graphics, c, text.Join("\n"), font, brush, glowBrush, 0, 0, format);
            }
            break;
        }
    }
 // If ControlStyles.AllPaintingInWmPaint, we call this method
 // after OnPaintBackground so it appears to OnPaint that it's getting a fresh
 // Graphics.  We want to make sure AllPaintingInWmPaint is purely an optimization,
 // and doesn't change behavior, so we need to make sure any clipping regions established
 // in OnPaintBackground don't apply to OnPaint. See ASURT 44682.
 internal void ResetGraphics() {
     if (graphics != null) {
         Debug.Assert(dc == IntPtr.Zero || savedGraphicsState != null, "Called ResetGraphics more than once?");
         if (savedGraphicsState != null) {
             graphics.Restore(savedGraphicsState);
             savedGraphicsState = null;
         }
     }
 }
		public void Restore (GraphicsState graphicsState) {
			if (ContainsGraphicsState(graphicsState)) {
				GraphicsState gs = PopGraphicsState();
				while ( gs != graphicsState )
					gs = PopGraphicsState();

				graphicsState.RestoreState(this);
			}
		}
 public GraphicsState Save()
 {
     var currentState = new GraphicsState();
     currentState.lastPen = LastPen;
     currentState.lastBrush = LastBrush;
     // Make sure we clone the Matrices or we will still modify
     // them after the save as they are the same objects.  Woops!!
     currentState.model = modelMatrix.Clone();
     currentState.view = viewMatrix.Clone();
     currentState.renderingOrigin = renderingOrigin;
     currentState.pageUnit = graphicsUnit;
     currentState.pageScale = pageScale;
     currentState.smoothingMode = smoothingMode;
     currentState.clipRegion = clipRegion;
     // I do not know if we should use the contexts save/restore state or our own
     // we will do that save state for now
     context.SaveState();
     return currentState;
 }
        // Operations
        public virtual void Draw(Graphics gs)
        {
            System.Drawing.Drawing2D.GraphicsState OldState = gs.Save();

            IntPtr hdc = new IntPtr();
            // get normalized rectangle
            Rectangle rect = m_rect;

            NormalizeRect(ref rect);

            // draw lines
            if ((m_nStyle & (StyleFlags.dottedLine | StyleFlags.solidLine)) != 0)
            {
                if ((m_nStyle & StyleFlags.dottedLine) != 0)
                {
                    BlackDottedPen.DashStyle = DashStyle.Dot;
                }
                else
                {
                    BlackDottedPen.DashStyle = DashStyle.Solid;
                }
                rect.Inflate(new Size(+1, +1));                   // borders are one pixel outside
                gs.DrawRectangle(BlackDottedPen, rect);
            }


            // hatch inside
            if ((m_nStyle & StyleFlags.hatchInside) != 0)
            {
                gs.FillRectangle(HatchBrush, rect.Left + 1, rect.Top + 1, rect.Width - 1, rect.Height - 1);
            }

            // draw hatched border
            if (true)            //(m_nStyle & StyleFlags.hatchedBorder) != 0)
            {
                Rectangle rectTrue = new Rectangle(0, 0, 0, 0);
                GetTrueRect(ref rectTrue);
                gs.FillRectangle(HatchBrush, rectTrue.Left, rectTrue.Top, rectTrue.Width, rect.Top - rectTrue.Top);
                gs.FillRectangle(HatchBrush, rectTrue.Left, rect.Bottom, rectTrue.Width, rectTrue.Bottom - rect.Bottom);
                gs.FillRectangle(HatchBrush, rectTrue.Left, rect.Top, rect.Left - rectTrue.Left, rect.Height);
                gs.FillRectangle(HatchBrush, rect.Right, rect.Top, rectTrue.Right - rect.Right, rect.Height);
            }

            // draw resize handles
            if ((m_nStyle & (StyleFlags.resizeInside | StyleFlags.resizeOutside)) != 0)
            {
                uint mask = GetHandleMask();
                for (int i = 0; i < 8; ++i)
                {
                    if ((mask & (1 << i)) != 0)
                    {
                        GetHandleRect(i, ref rect);
                        SolidBrush brush      = new SolidBrush(Color.Black);
                        Pen        pen        = new Pen(brush, 1);
                        SolidBrush brushWhite = new SolidBrush(Color.White);
                        gs.FillRectangle(brushWhite, rect);
                        gs.DrawRectangle(pen, rect);
                    }
                }
            }
            gs.Restore(OldState);
        }
Exemple #44
0
        public void Paint(Graphics g, IPlotArea layer, Processed2DPlotData pdata)
        {
            PlotRangeList rangeList = pdata.RangeList;

            PointF[] ptArray = pdata.PlotPointsInAbsoluteLayerCoordinates;

            // adjust the skip frequency if it was not set appropriate
            if (_skipFreq <= 0)
            {
                _skipFreq = 1;
            }

            // paint the drop style
            if (this.DropLine.Count > 0)
            {
                foreach (CSPlaneID id in _dropLine)
                {
                    layer.UpdateCSPlaneID(id);
                }

                int       rangeidx = 0;
                PlotRange range    = pdata.RangeList[rangeidx];
                for (int j = 0; j < ptArray.Length; j += _skipFreq)
                {
                    // syncronize range
                    while (j >= range.UpperBound)
                    {
                        rangeidx++;
                        range = pdata.RangeList[rangeidx];
                    }

                    Logical3D r3d = layer.GetLogical3D(pdata, j + range.OffsetToOriginal);
                    foreach (CSPlaneID id in _dropLine)
                    {
                        layer.CoordinateSystem.DrawIsolineFromPointToPlane(g, this._pen, r3d, id);
                    }
                }
            } // end paint the drop style


            // paint the scatter style
            if (this.Shape != XYPlotScatterStyles.Shape.NoSymbol)
            {
                // save the graphics stat since we have to translate the origin
                System.Drawing.Drawing2D.GraphicsState gs = g.Save();


                float xpos = 0, ypos = 0;
                float xdiff, ydiff;
                for (int j = 0; j < ptArray.Length; j += _skipFreq)
                {
                    xdiff = ptArray[j].X - xpos;
                    ydiff = ptArray[j].Y - ypos;
                    xpos  = ptArray[j].X;
                    ypos  = ptArray[j].Y;
                    g.TranslateTransform(xdiff, ydiff);
                    this.Paint(g);
                } // end for

                g.Restore(gs); // Restore the graphics state
            }
        }
Exemple #45
0
        private GraphicsPath _enclosingPath = new GraphicsPath(); // with Winding also overlapping rectangles are selected
        public override void Paint(Graphics g, XYPlotLayer layer, CSAxisInformation styleInfo, AxisLineStyle axisstyle, bool useMinorTicks)
        {
            _cachedStyleID = styleInfo.Identifier;
            CSLineID styleID = styleInfo.Identifier;
            Scale    raxis   = styleID.ParallelAxisNumber == 0 ? layer.XAxis : layer.YAxis;

            _enclosingPath.Reset();
            _enclosingPath.FillMode = FillMode.Winding; // with Winding also overlapping rectangles are selected
            GraphicsPath helperPath = new GraphicsPath();
            Matrix       math       = new Matrix();

            Logical3D r0 = _cachedStyleID.Begin;
            Logical3D r1 = _cachedStyleID.End;

            SizeF     layerSize = layer.Size;
            PointF    outVector;
            Logical3D outer;
            float     outerDistance = null == axisstyle? 0 : axisstyle.GetOuterDistance(styleInfo.PreferedLabelSide);
            float     dist_x        = outerDistance; // Distance from axis tick point to label
            float     dist_y        = outerDistance; // y distance from axis tick point to label

            // dist_x += this._font.SizeInPoints/3; // add some space to the horizontal direction in order to separate the chars a little from the ticks

            // next statement is necessary to have a consistent string length both
            // on 0 degree rotated text and rotated text
            // without this statement, the text is fitted to the pixel grid, which
            // leads to "steps" during scaling
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

            double[]        relpositions;
            AltaxoVariant[] ticks;
            if (useMinorTicks)
            {
                relpositions = raxis.GetMinorTicksNormal();
                ticks        = raxis.GetMinorTicksAsVariant();
            }
            else
            {
                relpositions = raxis.GetMajorTicksNormal();
                ticks        = raxis.GetMajorTicksAsVariant();
            }

            IMeasuredLabelItem[] labels = _labelFormatting.GetMeasuredItems(g, _font, _stringFormat, ticks);

            float emSize = _font.SizeInPoints;

            for (int i = 0; i < ticks.Length; i++)
            {
                double r = relpositions[i];

                outer = layer.CoordinateSystem.GetLogicalDirection(styleID.ParallelAxisNumber, styleInfo.PreferedLabelSide);
                PointF tickorg = layer.CoordinateSystem.GetNormalizedDirection(r0, r1, r, outer, out outVector);
                PointF tickend = tickorg;
                tickend.X += outVector.X * outerDistance;
                tickend.Y += outVector.Y * outerDistance;


                SizeF  msize = labels[i].Size;
                PointF morg  = tickend;

                if (_automaticRotationShift)
                {
                    double alpha = _rotation * Math.PI / 180 - Math.Atan2(outVector.Y, outVector.X);
                    double shift = msize.Height * 0.5 * Math.Abs(Math.Sin(alpha)) + (msize.Width + _font.SizeInPoints / 2) * 0.5 * Math.Abs(Math.Cos(alpha));
                    morg.X += (float)(outVector.X * shift);
                    morg.Y += (float)(outVector.Y * shift);
                }
                else
                {
                    morg.X += (float)(outVector.X * _font.SizeInPoints / 3);
                }


                RectangleF mrect = new RectangleF(morg, msize);
                if (_automaticRotationShift)
                {
                    AdjustRectangle(ref mrect, StringAlignment.Center, StringAlignment.Center);
                }
                else
                {
                    AdjustRectangle(ref mrect, _horizontalAlignment, _verticalAlignment);
                }

                math.Reset();
                math.Translate((float)morg.X, (float)morg.Y);
                if (this._rotation != 0)
                {
                    math.Rotate((float)-this._rotation);
                }
                math.Translate((float)(mrect.X - morg.X + emSize * _xOffset), (float)(mrect.Y - morg.Y + emSize * _yOffset));


                System.Drawing.Drawing2D.GraphicsState gs = g.Save();
                g.MultiplyTransform(math);

                if (this._backgroundStyle != null)
                {
                    _backgroundStyle.Draw(g, new RectangleF(PointF.Empty, msize));
                }

                _brush.Rectangle = new RectangleF(PointF.Empty, msize);
                labels[i].Draw(g, _brush, new PointF(0, 0));
                g.Restore(gs); // Restore the graphics state

                helperPath.Reset();
                helperPath.AddRectangle(new RectangleF(PointF.Empty, msize));
                helperPath.Transform(math);

                _enclosingPath.AddPath(helperPath, true);
            }
        }
        public void Restore(GraphicsState state)
        {
            if (stateStack == null)
            {
                stateStack = new object[MAX_GRAPHICS_STATE_STACK];
                statePos = 0;
            }

            if (state.nativeState > statePos)
                return;

            if (state.nativeState >= MAX_GRAPHICS_STATE_STACK)
                throw new OutOfMemoryException();

            var gstate = (CGGraphicsState)stateStack[state.nativeState];
            LastPen = gstate.lastPen;
            LastBrush = gstate.lastBrush;
            modelMatrix = gstate.model;
            viewMatrix = gstate.view;

            CompositingMode = gstate.compositingMode;
            CompositingQuality = gstate.compositingQuality;
            interpolationMode = gstate.interpolationMode;
            pageScale = gstate.pageScale;
            graphicsUnit = gstate.pageUnit;
            //PixelOffsetMode = gstate.pixelOffsetMode;
            SmoothingMode = gstate.smoothingMode;
            //TextContrast = gstate.textContrast;
            //TextRenderingHint = gstate.textRenderingHint;
            renderingOrigin = gstate.renderingOrigin;
            clipRegion = gstate.clipRegion;

            // re-apply our ModelView to the graphics context
            applyModelView();

            statePos = state.nativeState - 1;
        }
Exemple #47
0
        private void PaintOneRange(
            Graphics g,
            IPlotArea layer,
            PointF[] plotPositions,
            IPlotRange range,
            IScatterSymbol scatterSymbol,
            ref CachedPathData cachedPathData,
            ref CachedBrushData cachedBrushData)
        {
            var ptArray = plotPositions;

            float xpos = 0, ypos = 0;
            float xdiff, ydiff;

            int originalIndex;

            // save the graphics stat since we have to translate the origin
            System.Drawing.Drawing2D.GraphicsState gs = g.Save();

            if (null == _cachedSymbolSizeForIndexFunction && null == _cachedColorForIndexFunction) // using a constant symbol size
            {
                // calculate the path only once
                CalculatePaths(scatterSymbol, _symbolSize, ref cachedPathData);
                CalculateBrushes(scatterSymbol, _color, cachedPathData, ref cachedBrushData);

                for (int plotPointIndex = range.LowerBound; plotPointIndex < range.UpperBound; plotPointIndex += _skipFreq)
                {
                    xdiff = ptArray[plotPointIndex].X - xpos;
                    ydiff = ptArray[plotPointIndex].Y - ypos;
                    xpos  = ptArray[plotPointIndex].X;
                    ypos  = ptArray[plotPointIndex].Y;
                    g.TranslateTransform(xdiff, ydiff);

                    if (null != cachedPathData.InsetPath)
                    {
                        g.FillPath(cachedBrushData.InsetBrush, cachedPathData.InsetPath);
                    }

                    if (null != cachedPathData.FillPath)
                    {
                        g.FillPath(cachedBrushData.FillBrush, cachedPathData.FillPath);
                    }

                    if (null != cachedPathData.FramePath)
                    {
                        g.FillPath(cachedBrushData.FrameBrush, cachedPathData.FramePath);
                    }
                } // end for
            }
            else  // using a variable symbol size or variable symbol color
            {
                CalculatePaths(scatterSymbol, _symbolSize, ref cachedPathData);
                CalculateBrushes(scatterSymbol, _color, cachedPathData, ref cachedBrushData);

                for (int plotPointIndex = range.LowerBound; plotPointIndex < range.UpperBound; plotPointIndex += _skipFreq)
                {
                    originalIndex = range.GetOriginalRowIndexFromPlotPointIndex(plotPointIndex);

                    if (null == _cachedColorForIndexFunction)
                    {
                        double customSymbolSize = _cachedSymbolSizeForIndexFunction(originalIndex);
                        CalculatePaths(scatterSymbol, customSymbolSize, ref cachedPathData);
                    }
                    else
                    {
                        double customSymbolSize  = null == _cachedSymbolSizeForIndexFunction ? _symbolSize : _cachedSymbolSizeForIndexFunction(originalIndex);
                        var    customSymbolColor = _cachedColorForIndexFunction(originalIndex);
                        CalculatePaths(scatterSymbol, customSymbolSize, ref cachedPathData);
                        CalculateBrushes(scatterSymbol, NamedColor.FromArgb(customSymbolColor.A, customSymbolColor.R, customSymbolColor.G, customSymbolColor.B), cachedPathData, ref cachedBrushData);
                    }

                    xdiff = ptArray[plotPointIndex].X - xpos;
                    ydiff = ptArray[plotPointIndex].Y - ypos;
                    xpos  = ptArray[plotPointIndex].X;
                    ypos  = ptArray[plotPointIndex].Y;
                    g.TranslateTransform(xdiff, ydiff);

                    if (null != cachedPathData.InsetPath)
                    {
                        g.FillPath(cachedBrushData.InsetBrush, cachedPathData.InsetPath);
                    }

                    if (null != cachedPathData.FillPath)
                    {
                        g.FillPath(cachedBrushData.FillBrush, cachedPathData.FillPath);
                    }

                    if (null != cachedPathData.FramePath)
                    {
                        g.FillPath(cachedBrushData.FrameBrush, cachedPathData.FramePath);
                    }
                }
            }

            g.Restore(gs); // Restore the graphics state
        }
Exemple #48
0
        /// <summary>
        /// Raises the <see cref="PrintDocument.PrintPage"/> event. It is called before a page prints.
        /// </summary>
        /// <remarks>
        /// This method is overridden to print an Excel document.
        /// After doing its own work, it will call <see cref="PrintDocument.PrintPage"/> so you can draw your own thing over it.
        /// </remarks>
        /// <param name="e">A <see cref="PrintPageEventArgs"/> that contains the event data.</param>
        protected override void OnPrintPage(PrintPageEventArgs e)
        {
            // There is a bug in Vs2005 (but not in 2003) where the VisibleClipBounds property does not change with the PageUnit, and it remains the same as when the graphics was created.
            // See http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=230594  (VisibleClipBounds does not produce correct results for different PageUnit)
            // So, we are going to store the VisibleClipBounds here. It looks like if we do not call e.Graphics.Save, things work fine.


            // Other bug in the framework (and this is also in .NET 1.1)
            //This code alone in an OnPrintPage event:

            /*
             * e.Graphics.PageUnit=GraphicsUnit.Inch;
             * RectangleF r = e.Graphics.VisibleClipBounds;
             * e.Graphics.PageUnit=GraphicsUnit.Point;
             *
             * Font fnt = new Font("arial", 12, FontStyle.Underline);
             * e.Graphics.DrawString("hello", fnt, Brushes.Tomato, 100, 100);
             *
             * will not print the underline, even if printing to a virtual printer.
             * (preview will work fine). If instead of GraphicsUnit.Inch we use GraphicsUnit.Display,
             * Underline gets drawn in the wrong place!
             *
             * Using GraphicsUnit.Point in both places seems to fix it.
             */

            RectangleF   VisibleClipInches100;
            GraphicsUnit SaveUnits = e.Graphics.PageUnit;

            try
            {
                e.Graphics.PageUnit  = GraphicsUnit.Point; //NEEDS TO BE Point, since this is what we will use later. Other unit will confuse GDI+.
                VisibleClipInches100 = e.Graphics.VisibleClipBounds;
                VisibleClipInches100 = new RectangleF(VisibleClipInches100.X / 72F * 100, VisibleClipInches100.Y / 72F * 100,
                                                      VisibleClipInches100.Width / 72F * 100, VisibleClipInches100.Height / 72F * 100);
            }
            finally
            {
                e.Graphics.PageUnit = SaveUnits;
            }



            if (FRenderer == null || FRenderer.Workbook == null)
            {
                return;
            }
            System.Drawing.Drawing2D.GraphicsState InitialState = e.Graphics.Save();
            try
            {
                IFlxGraphics aCanvas = new GdiPlusGraphics(e.Graphics);

                //We could change the interpolation mode for images here.
                //e.Graphics.InterpolationMode = InterpolationMode.HighQualityBilinear;
                //e.Graphics.SmoothingMode = SmoothingMode.HighQuality;

                //e.Graphics.PageUnit=GraphicsUnit.Display;  //Display is not reliable as unit as it might change depending on the device. We will be using Point.
                e.Graphics.PageUnit = GraphicsUnit.Point;

                if (AntiAliasedText)
                {
                    e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
                }

                if (CurrentSheetPage == 1)
                {
                    FRenderer.SetCanvas(aCanvas);
                    MyPrintRange = FRenderer.InternalCalcPrintArea(FPrintRange);

                    if (CurrentWorkbookPage == 1 && AllVisibleSheets)
                    {
                        TotalWorkbookPages = GetPagesToPrint(e, aCanvas, VisibleClipInches100);
                    }
                    FRenderer.InitializePrint(aCanvas, ConvertToUnits(e.PageBounds, false),
                                              ConvertToMargins(e.Graphics, e.PageBounds, VisibleClipInches100, false), MyPrintRange, out PaintClipRect, out TotalSheetPages, out PagePrintRange);

                    if (!AllVisibleSheets)
                    {
                        TotalWorkbookPages = TotalSheetPages;
                    }

                    PagesToPrint = TotalWorkbookPages;

                    if (CurrentWorkbookPage == 1) //skip the first non printing pages.
                    {
                        if (PrinterSettings.FromPage > 0 && PrinterSettings.ToPage >= PrinterSettings.FromPage)
                        {
                            PagesToPrint = Math.Min(PrinterSettings.ToPage, TotalWorkbookPages);
                            for (int i = 1; i < PrinterSettings.FromPage; i++)
                            {
                                if (CurrentWorkbookPage > TotalWorkbookPages)
                                {
                                    return;
                                }
                                OnBeforePrintPage(e);
                                FRenderer.GenericPrint(aCanvas, ConvertToUnits(e.PageBounds, false), MyPrintRange, 0, PaintClipRect, 0, false, PagePrintRange, ref CurrentPrintArea);
                                IncCurrentPage();
                            }
                        }
                    }
                }

                if (CurrentWorkbookPage <= PagesToPrint)
                {
                    int CurrentPage = ResetPageNumberOnEachSheet ? CurrentSheetPage : CurrentWorkbookPage;
                    int TotalPages  = ResetPageNumberOnEachSheet ? TotalSheetPages : TotalWorkbookPages;
                    OnBeforePrintPage(e);
                    FRenderer.GenericPrint(aCanvas, ConvertToUnits(e.PageBounds, false), MyPrintRange, CurrentPage, PaintClipRect, TotalPages, true, PagePrintRange, ref CurrentPrintArea);
                    IncCurrentPage();
                }
                e.HasMorePages = CurrentWorkbookPage <= PagesToPrint;
            }
            finally
            {
                e.Graphics.Restore(InitialState);
            }
            base.OnPrintPage(e);
        }
		bool ContainsGraphicsState(GraphicsState state) {
			GraphicsState gs = _nextGraphicsState;

			while(gs != null) {
				if (gs == state)
					return true;

				gs = gs.Next;
			}

			return false;
		}
 internal XGraphicsState(GraphicsState state)
 {
   GdiState = state;
 }
Exemple #51
0
 protected void SetupTransform(Graphics g)
 {
     _state = g.Save();
     Matrix mx = new Matrix();
     if(_rotate)
         mx.Rotate(_rotation, MatrixOrder.Append);
     mx.Translate(this.Location.X, this.Location.Y, MatrixOrder.Append);
     g.Transform = mx;
 }