MakeEmpty() public method

public MakeEmpty ( ) : void
return void
Example #1
0
        /// <summary>
        /// Returns whether the given rectangle, in screen coordinates, is visible in any screen's
        /// working area (the monitor's visible area minus task bars and docked windows)</summary>
        /// <param name="rect">Rectangle</param>
        /// <returns>Whether the given rectangle is visible</returns>
        public static bool IsOnScreen(Rectangle rect)
        {
            using (Region region = new Region())
            {
                region.MakeEmpty();
                foreach (Screen screen in Screen.AllScreens)
                    region.Union(screen.WorkingArea);

                rect.Inflate(-Margin, -Margin);
                return region.IsVisible(rect);
            }
        }
Example #2
0
 /// <summary>
 /// Called when the form loads
 /// </summary>
 /// <param name="sender">what triggered the event</param>
 /// <param name="e">event args</param>
 private void MainForm_Load(object sender, EventArgs e)
 {
     // make cool shape
     Region r = new Region();
     GraphicsPath gp = new GraphicsPath();
     gp.AddEllipse(new Rectangle(0, 0, this.Width, this.Height));
     r.MakeEmpty();
     r.Union(gp);
     gp = new GraphicsPath();
     gp.AddRectangle(new Rectangle(this.Width / 2, 0, this.Width / 2, this.Height / 2));
     r.Union(gp);
     this.Region = r;
 }
        public Region CombineAreas()
        {
            Region region = new Region();
            region.MakeEmpty();

            foreach (Area area in Areas)
            {
                region.Union(area.Region);
            }

            region.Intersect(new Region(Crop.Bounds));

            return region;
        }
Example #4
0
 // Convert an Xsharp.Region to System.Drawing.Region
 internal static System.Drawing.Region RegionToDrawingRegion
     (Xsharp.Region region)
 {
     Xsharp.Rectangle[]    rectangles = region.GetRectangles();
     System.Drawing.Region newRegion  = new System.Drawing.Region();
     newRegion.MakeEmpty();
     for (int i = 0; i < rectangles.Length; i++)
     {
         Xsharp.Rectangle rect = rectangles[i];
         newRegion.Union(new System.Drawing.Rectangle
                             (rect.x, rect.y, rect.width, rect.height));
     }
     return(newRegion);
 }
Example #5
0
		protected override Region GetTabsRegion(TabsCollection tabs, TabItem lastTab)
		{
			bool bFirstVisible=true;
			Region tabRegion=new Region();
			tabRegion.MakeEmpty();
			foreach(TabItem tab in tabs)
			{
				if(!tab.Visible)
					continue;				
				GraphicsPath path=GetTabItemPath(tab,bFirstVisible,(tab==lastTab));
				tabRegion.Union(path);
				bFirstVisible=false;
			}
			return tabRegion;
		}
Example #6
0
        // Creates a new array and copies when we run out of space. Doubles the size.

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

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

            CalculateExtents(intersect);
            reg1.rects  = intersect.rects;
            reg1.extent = intersect.extent;
        }
        static BlockRegions()
        {
            int n = Constants.PROJ_WIDTH / 4;

            WholeBlock = new Region();
            WholeBlock.MakeEmpty();
            for (int i = 0; i <= n; i++)
            {
                WholeBlock.Union(new Rectangle(n * 2 - 1 - 2 * i, i, i * 4 + 2, Constants.PROJ_HEIGHT - 2 * i));
            }
            WholeBlock.Intersect(new Rectangle(0, 0, Constants.PROJ_WIDTH, Constants.PROJ_HEIGHT));
            InnerBlock = new Region();
            InnerBlock.MakeEmpty();
            for (int i = 0; i <= n; i++)
            {
                InnerBlock.Union(new Rectangle(n * 2 - 1 - 2 * i, i + 1, i * 4 + 2, Constants.PROJ_HEIGHT - 2 - 2 * i));
            }
            InnerBlock.Intersect(new Rectangle(1, 1, Constants.PROJ_WIDTH - 2, Constants.PROJ_HEIGHT - 2));

            OuterBorder = WholeBlock.Clone();
            OuterBorder.Exclude(InnerBlock);

            Top = InnerBlock.Clone();
            Top.Translate(0, -Constants.BLOCK_HEIGHT);
            Top.Intersect(InnerBlock);

            Left = InnerBlock.Clone();
            Left.Exclude(Top);
            Top.Translate(0, 1);
            Left.Exclude(Top);
            Top.Translate(0, -1);

            Right = Left.Clone();
            Left.Intersect(new Rectangle(0, 0, Constants.PROJ_WIDTH / 2, Constants.PROJ_HEIGHT));
            Right.Intersect(new Rectangle(Constants.PROJ_WIDTH / 2 + 1, 0, Constants.PROJ_WIDTH / 2, Constants.PROJ_HEIGHT));

            InnerBorder = InnerBlock.Clone();
            InnerBorder.Exclude(Top);
            InnerBorder.Exclude(Left);
            InnerBorder.Exclude(Right);
        }
 private Region GetRegion(Bitmap _img)
 {
     var rgn = new Region();
     rgn.MakeEmpty();
     var rc = new Rectangle(0, 0, 0, 0);
     bool inimage = false;
     for (int y = 0; y < _img.Height; y++)
     {
         for (int x = 0; x < _img.Width; x++)
         {
             if (!inimage)
             {
                 // if pixel is not transparent
                 if (_img.GetPixel(x, y).A != 0)
                 {
                     inimage = true;
                     rc.X = x;
                     rc.Y = y;
                     rc.Height = 1;
                 }
             }
             else
             {
                 // if pixel is transparent
                 if (_img.GetPixel(x, y).A == 0)
                 {
                     inimage = false;
                     rc.Width = x - rc.X;
                     rgn.Union(rc);
                 }
             }
         }
         if (inimage)
         {
             inimage = false;
             rc.Width = _img.Width - rc.X;
             rgn.Union(rc);
         }
     }
     return rgn;
 }
Example #9
0
 public Region this[int c]
 {
     get {
     if (this.cgrom[c] == null)
     {
         int C = c * charHeight;
         Region r = new Region();
         r.MakeEmpty();
         for (int y = 0; y < charHeight; ++y)
         {
             byte row = this.cgrom_raw[C + y];
             for (int x = 0; x < charWidth && row != 0; ++x)
             {
                 if ((row & 0x80) == 0x80)
                     r.Union(new Rectangle(x, y, 1, 1));
                 row <<= 1;
             }
         }
         this.cgrom[c] = r;
     }
     return this.cgrom[c];
     }
 }
Example #10
0
        private Region GetRegion(Rectangle bounds)
        {
            GraphicsPath path = GetFormPath(bounds);
            Region r = new Region();
            r.MakeEmpty();
            r.Union(path);

            // Widen path for the border...
            path.Widen(SystemPens.Control);
            Region r2 = new Region(path);
            r.Union(path);
            path.Dispose();
            return r;
        }
Example #11
0
        public void SetDataLabelsVisible( bool visible )
        {
            // set direct references
            ZedGraph.GraphPane pane = zedGraphControl1.GraphPane;
            ZedGraph.Axis xAxis = pane.XAxis;
            ZedGraph.Axis yAxis = pane.YAxis;

            if( CurrentGraphItem == null )
                return;

            //zedGraphControl1.GraphPane.GraphObjList.Clear();
            foreach( ZedGraph.GraphObj dataLabel in dataLabels )
                zedGraphControl1.GraphPane.GraphObjList.Remove( dataLabel );

            if( visible )
            {
                if( CurrentGraphItem.IsChromatogram )
                {
                    if( !( ChromatogramAnnotationSettings.ShowPointTimes ||
                        ChromatogramAnnotationSettings.ShowPointIntensities ||
                        ChromatogramAnnotationSettings.ShowUnmatchedAnnotations ||
                        ChromatogramAnnotationSettings.ShowMatchedAnnotations ) )
                        return;
                } else
                {
                    if( !( ScanAnnotationSettings.ShowPointMZs ||
                        ScanAnnotationSettings.ShowPointIntensities ||
                        ScanAnnotationSettings.ShowUnmatchedAnnotations ||
                        ScanAnnotationSettings.ShowMatchedAnnotations ) )
                        return;
                }

                yAxis.Scale.MinAuto = false;
                yAxis.Scale.Min = 0;

                // setup axes scales to enable the Transform method
                xAxis.Scale.SetupScaleData( pane, xAxis );
                yAxis.Scale.SetupScaleData( pane, yAxis );

                Graphics g = zedGraphControl1.CreateGraphics();
                System.Drawing.Bitmap gmap;

                if( pane.Chart.Rect.Width > 0 && pane.Chart.Rect.Height > 0 )
                {
                    try
                    {
                        //pane.Draw( g );
                        pane.CurveList.Draw( g, pane, 1.0f );
                        gmap = new Bitmap( Convert.ToInt32( pane.Rect.Width ), Convert.ToInt32( pane.Rect.Height ) );
                        zedGraphControl1.DrawToBitmap( gmap, Rectangle.Round( pane.Rect ) );
                    } catch
                    {
                        return;
                    }
                } else
                    return;

                Region textBoundsRegion;
                Region chartRegion = new Region( pane.Chart.Rect );
                Region clipRegion = new Region();
                clipRegion.MakeEmpty();
                g.SetClip( zedGraphControl1.MasterPane.Rect, CombineMode.Replace );
                g.SetClip( chartRegion, CombineMode.Exclude );
                /*Bitmap clipBmp = new Bitmap( Convert.ToInt32( pane.Rect.Width ), Convert.ToInt32( pane.Rect.Height ) );
                Graphics clipG = Graphics.FromImage( clipBmp );
                clipG.Clear( Color.White );
                clipG.FillRegion( new SolidBrush( Color.Black ), g.Clip );
                clipBmp.Save( "C:\\clip.bmp" );*/

                PointDataMap<SeemsPointAnnotation> matchedAnnotations = new PointDataMap<SeemsPointAnnotation>();

                // add precursor label(s) for tandem mass spectra
                if( CurrentGraphItem.IsMassSpectrum )
                {
                    MassSpectrum scanItem = (MassSpectrum) CurrentGraphItem;
                    pwiz.CLI.msdata.PrecursorList precursorList = scanItem.Element.spectrumDescription.precursors;
                    for( int i = 0; i < precursorList.Count; ++i )
                    {
                        pwiz.CLI.msdata.Precursor precursor = precursorList[i];
                        pwiz.CLI.msdata.SelectedIonList selectedIons = precursor.selectedIons;
                        if( selectedIons.Count == 0 )
                            continue;
                        double precursorMz = (double) selectedIons[0].cvParam( pwiz.CLI.msdata.CVID.MS_m_z ).value;
                        pwiz.CLI.msdata.CVParam precursorChargeParam = selectedIons[0].cvParam( pwiz.CLI.msdata.CVID.MS_charge_state );
                        int precursorCharge = 0;
                        if( precursorChargeParam.cvid != pwiz.CLI.msdata.CVID.CVID_Unknown )
                            precursorCharge = (int) selectedIons[0].cvParam( pwiz.CLI.msdata.CVID.MS_charge_state ).value;

                        float stickLength = ( yAxis.MajorTic.Size * 5 ) / pane.Chart.Rect.Height;
                        ZedGraph.LineObj stickOverlay = new ZedGraph.LineObj( precursorMz, 1, precursorMz, 1 + stickLength );
                        stickOverlay.Location.CoordinateFrame = ZedGraph.CoordType.XScaleYChartFraction;
                        stickOverlay.Line.Width = 3;
                        stickOverlay.Line.Style = DashStyle.Dot;
                        stickOverlay.Line.Color = Color.Green;
                        pane.GraphObjList.Add( stickOverlay );
                        dataLabels.Add( stickOverlay );

                        // Create a text label from the X data value
                        string precursorLabel;
                        if( precursorCharge > 0 )
                            precursorLabel = String.Format( "{0}\n(+{1} precursor)", precursorMz.ToString( "f3" ), precursorCharge );
                        else
                            precursorLabel = String.Format( "{0}\n(precursor of unknown charge)", precursorMz.ToString( "f3" ) );
                        ZedGraph.TextObj text = new ZedGraph.TextObj( precursorLabel, precursorMz, 1 + stickLength,
                            ZedGraph.CoordType.XScaleYChartFraction, ZedGraph.AlignH.Center, ZedGraph.AlignV.Top );
                        text.ZOrder = ZedGraph.ZOrder.A_InFront;
                        text.FontSpec.FontColor = stickOverlay.Line.Color;
                        text.FontSpec.Border.IsVisible = false;
                        text.FontSpec.Fill.IsVisible = false;
                        //text.FontSpec.Fill = new Fill( Color.FromArgb( 100, Color.White ) );
                        text.FontSpec.Angle = 0;

                        if( !detectLabelOverlap( pane, g, gmap, text, out textBoundsRegion ) )
                        {
                            pane.GraphObjList.Add( text );
                            clipRegion.Union( textBoundsRegion );
                            //g.SetClip( chartRegion, CombineMode.Replace );
                            g.SetClip( clipRegion, CombineMode.Replace );
                            //clipG.Clear( Color.White );
                            //clipG.FillRegion( new SolidBrush( Color.Black ), g.Clip );
                            //clipBmp.Save( "C:\\clip.bmp" );
                            dataLabels.Add( text );
                            //text.Draw( g, pane, 1.0f );
                            //zedGraphControl1.DrawToBitmap( gmap, Rectangle.Round( pane.Rect ) );
                        }
                    }
                }

                // add automatic labels
                foreach( ZedGraph.CurveItem curve in pane.CurveList )
                {
                    if( !( curve.Points is PointList ) )
                        continue;

                    PointList pointList = (PointList) curve.Points;
                    for( int i = 0; i < pointList.MaxCount; i++ )
                    {
                        ZedGraph.PointPair pt = pointList.GetPointAtIndex( pointList.ScaledMaxIndexList[i] );
                        if( pt.X < xAxis.Scale.Min || pt.Y > yAxis.Scale.Max || pt.Y < yAxis.Scale.Min )
                            continue;
                        if( pt.X > xAxis.Scale.Max )
                            break;

                        StringBuilder pointLabel = new StringBuilder();
                        Color pointColor = curve.Color;

                        // Add annotation
                        double annotationX = 0.0;
                        SeemsPointAnnotation annotation = null;
                        if( CurrentGraphItem.IsMassSpectrum )
                        {
                            PointDataMap<SeemsPointAnnotation>.MapPair annotationPair = ScanAnnotationSettings.PointAnnotations.FindNear( pt.X, ScanAnnotationSettings.MatchTolerance );
                            if( annotationPair != null )
                            {
                                annotationX = annotationPair.Key;
                                annotation = annotationPair.Value;
                                matchedAnnotations.Add( annotationPair );
                            }
                        } else
                        {
                            PointDataMap<SeemsPointAnnotation>.MapPair annotationPair = ChromatogramAnnotationSettings.PointAnnotations.FindNear( pt.X, ChromatogramAnnotationSettings.MatchTolerance );
                            if( annotationPair != null )
                            {
                                annotationX = annotationPair.Key;
                                annotation = annotationPair.Value;
                                matchedAnnotations.Add( annotationPair );
                            }
                        }

                        bool showMatchedAnnotations = false;
                        if( CurrentGraphItem.IsMassSpectrum )
                            showMatchedAnnotations = ScanAnnotationSettings.ShowMatchedAnnotations;
                        else
                            showMatchedAnnotations = ChromatogramAnnotationSettings.ShowMatchedAnnotations;

                        if( showMatchedAnnotations && annotation != null )
                        {
                            pointLabel.AppendLine( annotation.Label );
                            pointColor = annotation.Color;
                            //if( curve is ZedGraph.StickItem )
                            {
                                ZedGraph.LineObj stickOverlay = new ZedGraph.LineObj( annotationX, 0, annotationX, pt.Y );
                                //stickOverlay.IsClippedToChartRect = true;
                                stickOverlay.Location.CoordinateFrame = ZedGraph.CoordType.AxisXYScale;
                                stickOverlay.Line.Width = annotation.Width;
                                stickOverlay.Line.Color = pointColor;
                                zedGraphControl1.GraphPane.GraphObjList.Add( stickOverlay );
                                dataLabels.Add(stickOverlay);
                                //( (ZedGraph.StickItem) curve ).Color = pointColor;
                                //( (ZedGraph.StickItem) curve ).Line.Width = annotation.Width;
                            }
                        }

                        if( CurrentGraphItem.IsMassSpectrum )
                        {
                            if( ScanAnnotationSettings.ShowPointMZs )
                                pointLabel.AppendLine( pt.X.ToString( "f2" ) );
                            if( ScanAnnotationSettings.ShowPointIntensities )
                                pointLabel.AppendLine( pt.Y.ToString( "f2" ) );
                        } else
                        {
                            if( ChromatogramAnnotationSettings.ShowPointTimes )
                                pointLabel.AppendLine( pt.X.ToString( "f2" ) );
                            if( ChromatogramAnnotationSettings.ShowPointIntensities )
                                pointLabel.AppendLine( pt.Y.ToString( "f2" ) );
                        }

                        string pointLabelString = pointLabel.ToString();
                        if( pointLabelString.Length == 0 )
                            continue;

                        // Create a text label from the X data value
                        ZedGraph.TextObj text = new ZedGraph.TextObj( pointLabelString, pt.X, yAxis.Scale.ReverseTransform( yAxis.Scale.Transform( pt.Y ) - 5 ),
                            ZedGraph.CoordType.AxisXYScale, ZedGraph.AlignH.Center, ZedGraph.AlignV.Bottom );
                        text.ZOrder = ZedGraph.ZOrder.A_InFront;
                        //text.IsClippedToChartRect = true;
                        text.FontSpec.FontColor = pointColor;
                        // Hide the border and the fill
                        text.FontSpec.Border.IsVisible = false;
                        text.FontSpec.Fill.IsVisible = false;
                        //text.FontSpec.Fill = new Fill( Color.FromArgb( 100, Color.White ) );
                        // Rotate the text to 90 degrees
                        text.FontSpec.Angle = 0;

                        if( !detectLabelOverlap( pane, g, gmap, text, out textBoundsRegion ) )
                        {
                            pane.GraphObjList.Add( text );
                            clipRegion.Union( textBoundsRegion );
                            //g.SetClip( chartRegion, CombineMode.Replace );
                            g.SetClip( clipRegion, CombineMode.Replace );
                            //clipG.Clear( Color.White );
                            //clipG.FillRegion( new SolidBrush( Color.Black ), g.Clip );
                            //clipBmp.Save( "C:\\clip.bmp" );
                            dataLabels.Add( text );
                            //text.Draw( g, pane, 1.0f );
                            //zedGraphControl1.DrawToBitmap( gmap, Rectangle.Round( pane.Rect ) );
                        }
                    }
                }

                bool showUnmatchedAnnotations = false;
                if( CurrentGraphItem.IsMassSpectrum )
                    showUnmatchedAnnotations = ScanAnnotationSettings.ShowUnmatchedAnnotations;
                else
                    showUnmatchedAnnotations = ChromatogramAnnotationSettings.ShowUnmatchedAnnotations;

                if( showUnmatchedAnnotations )
                {
                    PointDataMap<SeemsPointAnnotation> annotations = CurrentPointAnnotations;

                    foreach( PointDataMap<SeemsPointAnnotation>.MapPair annotationPair in annotations )
                    {
                        if( matchedAnnotations.Contains( annotationPair ) )
                            continue;

                        float stickLength = ( yAxis.MajorTic.Size * 2 ) / pane.Chart.Rect.Height;
                        ZedGraph.LineObj stickOverlay = new ZedGraph.LineObj( annotationPair.Key, 1, annotationPair.Key, 1 + stickLength );
                        //stickOverlay.IsClippedToChartRect = true;
                        stickOverlay.Location.CoordinateFrame = ZedGraph.CoordType.XScaleYChartFraction;
                        stickOverlay.Line.Width = annotationPair.Value.Width;
                        stickOverlay.Line.Color = annotationPair.Value.Color;
                        zedGraphControl1.GraphPane.GraphObjList.Add( stickOverlay );
                        dataLabels.Add( stickOverlay );
                    }
                }
                g.Dispose();
            } else
            {
                // remove labels
            }
        }
        //This function will give snapshot of what is drawn on the screen at any point of time
        //It will scale and translate the designers and drawing based on the viewport data
        //We need this function in OnPaint and taking snapshot of magnifier bitmap
        //At the end of this function; the ViewPortData.MemoryBitmap will contain the bitmap of the 
        //workflow to be drawn as per layout
        internal static void TakeWorkflowSnapShot(WorkflowView workflowView, ViewPortData viewPortData)
        {
            //Get the drawing canvas
            Bitmap memoryBitmap = viewPortData.MemoryBitmap;
            Debug.Assert(memoryBitmap != null);

            using (Graphics viewPortGraphics = Graphics.FromImage(memoryBitmap))
            {
                //We set the highest quality interpolation so that we do not loose the image quality
                viewPortGraphics.SmoothingMode = SmoothingMode.HighQuality;
                viewPortGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

                using (PaintEventArgs eventArgs = new PaintEventArgs(viewPortGraphics, viewPortData.LogicalViewPort))
                {
                    workflowView.ActiveLayout.OnPaint(eventArgs, viewPortData);
                }

                //Create the scaling matrix 
                Matrix transformationMatrix = new Matrix();
                transformationMatrix.Scale(viewPortData.Scaling.Width, viewPortData.Scaling.Height, MatrixOrder.Prepend);

                //When we draw on the viewport we draw in scaled and translated. 
                //So that we minimize the calls to DrawImage
                //Make sure that we scale down the logical view port origin in order to take care of scaling factor
                //Before we select the transform factor we make sure that logicalviewport origin is scaled down
                Point[] logicalViewPortOrigin = new Point[] { viewPortData.LogicalViewPort.Location };
                transformationMatrix.TransformPoints(logicalViewPortOrigin);

                //For performance improvement and to eliminate one extra DrawImage...we draw the designers on the viewport
                //bitmap with visual depth consideration
                transformationMatrix.Translate(-logicalViewPortOrigin[0].X + viewPortData.ShadowDepth.Width, -logicalViewPortOrigin[0].Y + viewPortData.ShadowDepth.Height, MatrixOrder.Append);

                //Select the transform into viewport graphics.
                //Viewport bitmap has the scaled and translated designers which we then map to
                //the actual graphics based on page layout
                viewPortGraphics.Transform = transformationMatrix;

                //Draw the designers on bitmap
                if (workflowView.RootDesigner != null)
                {
                    using (Region clipRegion = new Region())
                    using (GraphicsPath designerPath = ActivityDesignerPaint.GetDesignerPath(workflowView.RootDesigner, false))
                    {
                        Region oldRegion = viewPortGraphics.Clip;

                        //First draw the grid and rectangle with the designer clip region
                        clipRegion.MakeEmpty();
                        clipRegion.Union(designerPath);
                        viewPortGraphics.Clip = clipRegion;
                        AmbientTheme ambientTheme = WorkflowTheme.CurrentTheme.AmbientTheme;
                        viewPortGraphics.FillRectangle(ambientTheme.BackgroundBrush, workflowView.RootDesigner.Bounds);
                        if (ambientTheme.ShowGrid)
                            ActivityDesignerPaint.DrawGrid(viewPortGraphics, workflowView.RootDesigner.Bounds);
                        viewPortGraphics.Clip = oldRegion;

                        //Then draw the root with clip region extended
                        try
                        {
                            using (PaintEventArgs paintEventArgs = new PaintEventArgs(viewPortGraphics, viewPortData.LogicalViewPort))
                            {
                                ((IWorkflowDesignerMessageSink)workflowView.RootDesigner).OnPaint(paintEventArgs, viewPortData.LogicalViewPort);
                            }
                        }
                        catch (Exception e)
                        {
                            //Eat the exception thrown in draw
                            Debug.WriteLine(e);
                        }
                    }
                }

                //Draw all the filters


                using (PaintEventArgs paintArgs = new PaintEventArgs(viewPortGraphics, workflowView.RootDesigner.Bounds))
                {
                    using (WorkflowMessageDispatchData dispatchData = new WorkflowMessageDispatchData(workflowView, EventArgs.Empty))
                    {
                        foreach (WorkflowDesignerMessageFilter filter in dispatchData.Filters)
                        {
                            try
                            {
                                if (((IWorkflowDesignerMessageSink)filter).OnPaint(paintArgs, viewPortData.LogicalViewPort))
                                    break;
                            }
                            catch (Exception e)
                            {
                                Debug.WriteLine(e);
                            }
                        }
                    }
                }

                viewPortGraphics.Transform = new Matrix();

                //Now that we have a bitmap which is bit offseted based visual depth we need to take copy of it
                //This is done so as to avoid expensive DrawImage call, what I am assuming here is that time it 
                //will take to create a new bitmap from an existing one is less expensive in terms of speed than space
                //As you just need to copy bitmap bits in memory than to perform expesive Image Drawing operation
                if (!viewPortData.ShadowDepth.IsEmpty)
                {
                    Bitmap temporaryBitmap = new Bitmap(memoryBitmap);

                    //THEMETODO: WE JUST NEED TO GRAYSCALE THIS, RATHER THAN DRAWING A SHADOW
                    //Now that we have taken a copy we will draw over the existing bitmap so that we can make it as shadow bitmap
                    using (Brush shadowDepthBrush = new SolidBrush(Color.FromArgb(220, Color.White)))
                        viewPortGraphics.FillRectangle(shadowDepthBrush, new Rectangle(Point.Empty, new Size(memoryBitmap.Size.Width - viewPortData.ShadowDepth.Width - 1, memoryBitmap.Size.Height - viewPortData.ShadowDepth.Height - 1)));

                    //Now make sure that we draw the image from the temporary bitmap with white color set as transparent 
                    //so that we achive the 3D effect
                    //Make sure that we take into consideration the transparency key
                    ImageAttributes transparentColorKey = new ImageAttributes();
                    transparentColorKey.SetColorKey(viewPortData.TransparentColor, viewPortData.TransparentColor, ColorAdjustType.Default);
                    transparentColorKey.SetColorKey(viewPortData.TransparentColor, viewPortData.TransparentColor, ColorAdjustType.Bitmap);
                    viewPortGraphics.DrawImage(temporaryBitmap, new Rectangle(-viewPortData.ShadowDepth.Width, -viewPortData.ShadowDepth.Height, memoryBitmap.Width, memoryBitmap.Height), 0, 0, memoryBitmap.Width, memoryBitmap.Height, GraphicsUnit.Pixel, transparentColorKey);

                    //Now dispose the temporary bitmap
                    temporaryBitmap.Dispose();
                }
            }
        }
Example #13
0
        //Format24bppRgb・Format32bppRgb・Format32bppArgb
        //http://d.hatena.ne.jp/aharisu/20090523/1243077727
        //コードは上記より拝借
        public Region CreateRegionFromBitmap(Bitmap bitmap)
        {
            if (!(bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format24bppRgb ||
                bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb ||
                bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppRgb))
                return null;// 24bitか32bit以外は無理

            //ここの変数もっとまともな名前つけたい
            int channels = Image.GetPixelFormatSize(bitmap.PixelFormat) / 8;
            int offset = 0;
            int count = channels;
            if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
            {//Format32bppArgbの場合はα値のみを確認する
                count = 1;
                offset = 3;
            }

            //ビットマップから生データを取得
            Rectangle rectBitmap = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
            System.Drawing.Imaging.BitmapData data = bitmap.LockBits(rectBitmap,
                System.Drawing.Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat);
            byte[] values = new byte[data.Height * data.Stride];
            System.Runtime.InteropServices.Marshal.Copy(data.Scan0, values, 0, data.Height * data.Stride);
            bitmap.UnlockBits(data);

            //透明にする色を取得
            byte[] transparent = new byte[count];
            if (count == 1)
                transparent[0] = 0;
            else
            {
                for (int i = 0; i < count; ++i)
                    transparent[i] = values[i];
            }

            Region region = new Region();
            region.MakeEmpty();

            Rectangle rect = new Rectangle();
            for (int y = 0; y < data.Height; ++y)
            {
                int offsetY = y * data.Stride;
                for (int x = 0; x < data.Width; ++x)
                {
                    for (int c = 0; c < count; ++c)
                    {
                        if (transparent[c] != values[offsetY + x * channels + c + offset])
                        {//透過色ではない
                            rect.X = x;//透過色ではないスタート地点を保存
                            for (++x; x < data.Width; ++x)
                            {
                                for (c = 0; c < count; ++c)
                                {
                                    if (transparent[c] != values[offsetY + x * channels + c + offset])
                                        goto CONTINUE;	//透過色ではないので続ける
                                }
                                break;	//次の透過色を見つけたので脱出
                            CONTINUE:
                                ;
                            }
                            rect.Width = x - rect.X;
                            rect.Y = y;
                            rect.Height = 1;

                            //透過色でない部分をリージョンに追加する
                            region.Union(rect);
                            break;
                        }
                    }
                }
            }

            return region;
        }
 /// <summary>
 /// OnPaint will go through the enabled elements (vertical ReminderMessage, GridLines, LineNumbers, BorderLines,
 /// MarginLines) and will draw them if enabled. At the same time, it will build GraphicsPaths for each of those
 /// elements (that are enabled), which will be used in SeeThroughMode (if it's active): the figures in the
 /// GraphicsPaths will form a customized outline for the control by setting them as the Region of the LineNumber
 /// control. Note: the vertical ReminderMessages are only drawn during designtime. 
 /// </summary>
 /// <param name="e"></param>
 protected override void OnPaint(PaintEventArgs e)
 {
     // Build the list of visible LineNumberItems (= pLineNumberItems) first. (doesn't take long, so it can stay in OnPaint)
     UpdateVisibleLineNumberItems();
     base.OnPaint(e);
     // Quality settings
     e.Graphics.TextRenderingHint = pLineNumbersAntiAlias ? TextRenderingHint.AntiAlias : TextRenderingHint.SystemDefault;
     // NOTE: The GraphicsPaths are only used for SeeThroughMode
     // FillMode.Winding: combined outline ( Alternate: XOR'ed outline )
     GraphicsPath gpGridLines = new GraphicsPath(FillMode.Winding);
     GraphicsPath gpBorderLines = new GraphicsPath(FillMode.Winding);
     GraphicsPath gpMarginLines = new GraphicsPath(FillMode.Winding);
     GraphicsPath gpLineNumbers = new GraphicsPath(FillMode.Winding);
     if (DesignMode)
     {
         string reminderToShow = string.Empty;
         if (RTParent == null)
         {
             reminderToShow = "-!- Set ParentRichTextBox -!-";
         }
         else if (pLineNumberItems.Count == 0)
         {
             reminderToShow = "LineNumbers (  " + RTParent.Name + "  )";
         }
         if (reminderToShow.Length > 0)
         {
             e.Graphics.TranslateTransform(Width / 2f, Height / 2f);
             e.Graphics.RotateTransform(-90f);
             StringFormat format = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center };
             SizeF textSize = e.Graphics.MeasureString(reminderToShow, Font, new Point(0, 0), format);
             e.Graphics.DrawString(reminderToShow, Font, Brushes.WhiteSmoke, 1f, 1f, format);
             e.Graphics.DrawString(reminderToShow, Font, Brushes.Firebrick, 0f, 0f, format);
             e.Graphics.ResetTransform();
             Rectangle reminderRectangle = new Rectangle((int)Math.Round((Width / 2.0) - (textSize.Height / 2.0)),
                                                          (int)Math.Round((Height / 2.0) - (textSize.Width / 2.0)),
                                                          (int)Math.Round(textSize.Height), (int)Math.Round(textSize.Width));
             gpLineNumbers.AddRectangle(reminderRectangle);
             gpLineNumbers.CloseFigure();
             if (pAutoSizing)
             {
                 reminderRectangle.Inflate((int)Math.Round(textSize.Height * 0.2), (int)Math.Round(textSize.Width * 0.1));
                 pAutoSizingSize = new Size(reminderRectangle.Width, reminderRectangle.Height);
             }
         }
     }
     if (pLineNumberItems.Count > 0)
     {
         // The visible LineNumberItems with their BackgroundGradient and GridLines
         // Loop through every visible LineNumberItem
         using (Pen pen = new Pen(pGridLinesColor, pGridLinesThickness) { DashStyle = pGridLinesStyle })
         {
             StringFormat format = new StringFormat
             {
                 Alignment = StringAlignment.Near,
                 LineAlignment = StringAlignment.Near,
                 FormatFlags =
                     StringFormatFlags.NoClip | StringFormatFlags.NoWrap | StringFormatFlags.FitBlackBox
             };
             for (int i = 0; i <= pLineNumberItems.Count - 1; i++)
             {
                 // Background gradient
                 if (pGradientShow)
                 {
                     using (LinearGradientBrush brush = new LinearGradientBrush(pLineNumberItems[i].Rectangle,
                         pGradientStartColor, pGradientEndColor, pGradientDirection))
                     {
                         e.Graphics.FillRectangle(brush, pLineNumberItems[i].Rectangle);
                     }
                 }
                 // Grid lines
                 if (pGridLinesShow)
                 {
                     e.Graphics.DrawLine(pen, new Point(0, pLineNumberItems[i].Rectangle.Y),
                         new Point(Width, pLineNumberItems[i].Rectangle.Y));
                     Rectangle rect = new Rectangle((int)Math.Round(-pGridLinesThickness), pLineNumberItems[i].Rectangle.Y,
                         (int)Math.Round(Width + (pGridLinesThickness * 2.0)),
                         (int)Math.Round((Height - pLineNumberItems[0].Rectangle.Y) + pGridLinesThickness));
                     gpGridLines.AddRectangle(rect);
                     gpGridLines.CloseFigure();
                 }
                 // Line numbers
                 if (pLineNumbersShow)
                 {
                     string textToShow;
                     if (pLineNumbersShowLeadingZeroes)
                     {
                         textToShow = pLineNumbersShowAsHexadecimal
                                         ? pLineNumberItems[i].LineNumber.ToString("X4")
                                         : pLineNumberItems[i].LineNumber.ToString("D4");
                     }
                     else
                     {
                         textToShow = pLineNumbersShowAsHexadecimal
                                         ? pLineNumberItems[i].LineNumber.ToString("X4")
                                         : pLineNumberItems[i].LineNumber.ToString("D4");
                     }
                     Point point = new Point(0, 0);
                     SizeF textSize = e.Graphics.MeasureString(textToShow, Font, point, format);
                     // Text alignment
                     point = GetAlignmentPoint(textSize, pLineNumberItems[i]);
                     // Text clipping
                     Rectangle itemClipRectangle = new Rectangle(point, textSize.ToSize());
                     if (pLineNumbersClipByItemRectangle)
                     {
                         // If selected, the text will be clipped so that it doesn't spill out of its own
                         // LineNumberItem-area. Only the part of the text inside the LineNumberItem.
                         // Rectangle should be visible, so intersect with the ItemRectangle.
                         // The SetClip method temporary restricts the drawing area of the control for whatever
                         // is drawn next.
                         itemClipRectangle.Intersect(pLineNumberItems[i].Rectangle);
                         e.Graphics.SetClip(itemClipRectangle);
                     }
                     // Text drawing
                     using (SolidBrush brush = new SolidBrush(ForeColor))
                     {
                         e.Graphics.DrawString(textToShow, Font, brush, point, format);
                         e.Graphics.ResetClip();
                     }
                     // The GraphicsPath for the LineNumber is just a rectangle behind the text, to keep the paintingspeed high and avoid ugly artifacts.
                     gpLineNumbers.AddRectangle(itemClipRectangle);
                     gpLineNumbers.CloseFigure();
                 }
             }
             // Grid lines thickness and linestyle in SeeThroughMode. All GraphicsPath lines are drawn as solid to keep the paintingspeed high.
             if (pGridLinesShow)
             {
                 pen.DashStyle = DashStyle.Solid;
                 gpGridLines.Widen(pen);
             }
         }
     }
     Point left = new Point((int)Math.Round(Math.Floor(pBorderLinesThickness / 2.0)),
                              (int)Math.Round(Math.Floor(pBorderLinesThickness / 2.0)));
     Point right = new Point((int)Math.Round(Width - Math.Ceiling(pBorderLinesThickness / 2.0)),
                               (int)Math.Round(Height - Math.Ceiling(pBorderLinesThickness / 2.0)));
     // Border lines
     Point[] borderLinesPoints = new Point[5];
     borderLinesPoints[0] = new Point(left.X, left.Y);
     borderLinesPoints[1] = new Point(right.X, left.Y);
     borderLinesPoints[2] = new Point(right.X, right.Y);
     borderLinesPoints[3] = new Point(left.X, right.Y);
     borderLinesPoints[4] = new Point(left.X, left.Y);
     if (pBorderLinesShow)
     {
         using (Pen pen = new Pen(pBorderLinesColor, pBorderLinesThickness) { DashStyle = pBorderLinesStyle })
         {
             e.Graphics.DrawLines(pen, borderLinesPoints);
             gpBorderLines.AddLines(borderLinesPoints);
             gpBorderLines.CloseFigure();
             pen.DashStyle = DashStyle.Solid;
             gpBorderLines.Widen(pen);
         }
     }
     // Margin lines
     if (pMarginLinesShow && (pMarginLinesSide > LineNumberDockSide.None))
     {
         left = new Point((int)Math.Round(-pMarginLinesThickness), (int)Math.Round(-pMarginLinesThickness));
         right = new Point((int)Math.Round(Width + pMarginLinesThickness),
                             (int)Math.Round(Height + pMarginLinesThickness));
         using (Pen pen = new Pen(pMarginLinesColor, pMarginLinesThickness) { DashStyle = pMarginLinesStyle })
         {
             if ((pMarginLinesSide == LineNumberDockSide.Left) | (pMarginLinesSide == LineNumberDockSide.Height))
             {
                 e.Graphics.DrawLine(pen, new Point((int)Math.Round(Math.Floor(pMarginLinesThickness / 2.0)), 0),
                                     new Point((int)Math.Round(Math.Floor(pMarginLinesThickness / 2.0)), Height - 1));
                 left = new Point((int)Math.Round(Math.Ceiling(pMarginLinesThickness / 2.0)),
                                    (int)Math.Round(-pMarginLinesThickness));
             }
             if ((pMarginLinesSide == LineNumberDockSide.Right) | (pMarginLinesSide == LineNumberDockSide.Height))
             {
                 e.Graphics.DrawLine(pen, new Point((int)Math.Round(Width - Math.Ceiling(pMarginLinesThickness / 2.0)), 0),
                                     new Point((int)Math.Round(Width - Math.Ceiling(pMarginLinesThickness / 2.0)), Height - 1));
                 right = new Point((int)Math.Round(Width - Math.Ceiling(pMarginLinesThickness / 2.0)),
                                     (int)Math.Round(Height + pMarginLinesThickness));
             }
             // GraphicsPath for the MarginLines(s): MarginLines(s) are drawn as a rectangle connecting the left
             // and right points, which are either inside or outside of sight, depending on whether the MarginLines
             // at that side is visible. "left": TopLeft and "right": BottomRight
             gpMarginLines.AddRectangle(new Rectangle(left, new Size(right.X - left.X, right.Y - left.Y)));
             pen.DashStyle = DashStyle.Solid;
             gpMarginLines.Widen(pen);
         }
     }
     Region region = new Region(ClientRectangle);
     // SeeThroughMode: combine all the GraphicsPaths and set them as the region for the control.
     if (pSeeThroughMode)
     {
         region.MakeEmpty();
         region.Union(gpBorderLines);
         region.Union(gpMarginLines);
         region.Union(gpGridLines);
         region.Union(gpLineNumbers);
     }
     if (region.GetBounds(e.Graphics).IsEmpty)
     {
         // Note: If the control is in a condition that would show it as empty, then a border-region is still
         // drawn regardless of it's borders on/off state. This is added to make sure that the bounds of the
         // control are never lost (it would remain empty if this was not done).
         gpBorderLines.AddLines(borderLinesPoints);
         gpBorderLines.CloseFigure();
         using (Pen pen = new Pen(pBorderLinesColor, 1f) { DashStyle = DashStyle.Solid })
         {
             gpBorderLines.Widen(pen);
             region = new Region(gpBorderLines);
         }
     }
     Region = region;
 }
			protected override void OnMouseMove (MouseEventArgs e)
			{
				ButtonState before, after;

				before = ButtonState.Normal;
				if ((mouse_pressed == 1) && top_button_rect.Contains(mouse_x, mouse_y))
					before = ButtonState.Pushed;
				if ((mouse_pressed == 2) && bottom_button_rect.Contains(mouse_x, mouse_y))
					before = ButtonState.Pushed;

				mouse_x = e.X;
				mouse_y = e.Y;

				after = ButtonState.Normal;
				if ((mouse_pressed == 1) && top_button_rect.Contains(mouse_x, mouse_y))
					after = ButtonState.Pushed;
				if ((mouse_pressed == 2) && bottom_button_rect.Contains(mouse_x, mouse_y))
					after = ButtonState.Pushed;

				bool new_top_button_entered = top_button_rect.Contains (e.Location);
				bool new_bottom_button_entered = bottom_button_rect.Contains (e.Location);
				
				if (before != after) {
					if (after == ButtonState.Pushed) {
						tmrRepeat.Enabled = true;
						repeat_counter = 0;
						repeat_delay = InitialRepeatDelay;

						// fire off one right now too for good luck
						if (mouse_pressed == 1)
							owner.UpButton();
						if (mouse_pressed == 2)
							owner.DownButton();
					}
					else
						tmrRepeat.Enabled = false;

					top_button_entered = new_top_button_entered;
					bottom_button_entered = new_bottom_button_entered;

					Refresh ();
				} else {
					if (ThemeEngine.Current.UpDownBaseHasHotButtonStyle) {
						Region area_to_invalidate = new Region ();
						bool dirty = false;
						area_to_invalidate.MakeEmpty ();
						if (top_button_entered != new_top_button_entered) {
							top_button_entered = new_top_button_entered;
							area_to_invalidate.Union (top_button_rect);
							dirty = true;
						}
						if (bottom_button_entered != new_bottom_button_entered) {
							bottom_button_entered = new_bottom_button_entered;
							area_to_invalidate.Union (bottom_button_rect);
							dirty = true;
						}
						if (dirty)
							Invalidate (area_to_invalidate);
						area_to_invalidate.Dispose ();
					} else {
						top_button_entered = new_top_button_entered;
						bottom_button_entered = new_bottom_button_entered;
					}
				}
			}
Example #16
0
		public void EmptyRegionWithInfiniteRegion ()
		{
			Region empty = new Region ();
			empty.MakeEmpty ();
			Assert.IsTrue (empty.IsEmpty (graphic), "IsEmpty");

			Region region = new Region ();
			Assert.IsTrue (region.IsInfinite (graphic), "IsInfinite");

			region.Union (empty);
			Assert.IsTrue (region.IsInfinite (graphic), "Union-IsInfinite");

			region.Xor (empty);
			Assert.IsTrue (region.IsInfinite (graphic), "Xor-IsInfinite");

			region.Exclude (empty);
			Assert.IsTrue (region.IsInfinite (graphic), "Exclude-IsInfinite");

			region.Intersect (empty);
			Assert.IsTrue (region.IsEmpty (graphic), "Intersect-IsEmpty");

			region.MakeInfinite ();
			region.Complement (empty);
			Assert.IsTrue (region.IsEmpty (graphic), "Complement-IsEmpty");
		}
        public Region getRegion()
        {
            GraphicsPath gp = new GraphicsPath();
            gp.AddLine(origin, destination);
            Region region = new Region();
            int l = Math.Min(source.Bounds.Left, target.Bounds.Left);
            int t = Math.Min(source.Bounds.Top, target.Bounds.Top);
            int r = Math.Max(source.Bounds.Right, target.Bounds.Right);
            int b = Math.Max(source.Bounds.Bottom, target.Bounds.Bottom);

            Rectangle rect = new Rectangle(1, t, r-1, b-t);
            region.MakeEmpty();
            region.Union(rect);
            return region;
        }
Example #18
0
        //,   Color   TransparentColor)
        private static Region BmpRgn(Bitmap Picture)
        {
            #region

            int nWidth = Picture.Width;
            int nHeight = Picture.Height;
            Region rgn = new Region();
            rgn.MakeEmpty();
            bool isTransRgn; //ǰһ�����Ƿ���͸����
            Color curColor; //��ǰ�����ɫ
            Rectangle curRect = new Rectangle();
            curRect.Height = 1;
            int x = 0, y = 0;
            Color TransparentColor = Picture.GetPixel(0, 0);
            //������ɨ�����ͼƬ���ҳ���͸��ɫ�������򲢺ϲ�����
            for (y = 0; y < nHeight; ++y)
            {
                isTransRgn = true;
                for (x = 0; x < nWidth; ++x)
                {
                    curColor = Picture.GetPixel(x, y);
                    if (curColor == TransparentColor || x == nWidth - 1) //�������͸��ɫ����β
                    {
                        if (isTransRgn == false) //�˳���Ч��
                        {
                            curRect.Width = x - curRect.X;
                            rgn.Union(curRect);
                        }
                    }
                    else //��͸��ɫ
                    {
                        if (isTransRgn == true) //��������
                        {
                            curRect.X = x;
                            curRect.Y = y;
                        }
                    } //if   curColor
                    isTransRgn = curColor == TransparentColor;
                } //for   x
            } //for   y
            return rgn;

            #endregion
        }
		internal override PaintEventArgs PaintEventStart(ref Message msg, IntPtr handle, bool client) {
			PaintEventArgs	paint_event;
			Hwnd		hwnd;
			Hwnd		paint_hwnd; 
			
			hwnd = Hwnd.ObjectFromHandle(msg.HWnd);
			if (msg.HWnd == handle) {
				paint_hwnd = hwnd;
			} else {
				paint_hwnd = Hwnd.ObjectFromHandle (handle);
			}
			
			if (Caret.Visible == 1) {
				Caret.Paused = true;
				HideCaret();
			}

			Graphics dc;

			if (client) {
				dc = Graphics.FromHwnd (paint_hwnd.client_window);

				Region clip_region = new Region ();
				clip_region.MakeEmpty();

				foreach (Rectangle r in hwnd.ClipRectangles) {
					clip_region.Union (r);
				}

				if (hwnd.UserClip != null) {
					clip_region.Intersect(hwnd.UserClip);
				}

				// FIXME: Clip region is hosed
				dc.Clip = clip_region;
				paint_event = new PaintEventArgs(dc, hwnd.Invalid);
				hwnd.expose_pending = false;
				hwnd.ClearInvalidArea();

				hwnd.drawing_stack.Push (paint_event);
				hwnd.drawing_stack.Push (dc);
			} else {
				dc = Graphics.FromHwnd (paint_hwnd.whole_window);

				if (!hwnd.nc_invalid.IsEmpty) {
					// FIXME: Clip region is hosed
					dc.SetClip (hwnd.nc_invalid);
					paint_event = new PaintEventArgs(dc, hwnd.nc_invalid);
				} else {
					paint_event = new PaintEventArgs(dc, new Rectangle(0, 0, hwnd.width, hwnd.height));
				}
				hwnd.nc_expose_pending = false;
				hwnd.ClearNcInvalidArea ();

				hwnd.drawing_stack.Push (paint_event);
				hwnd.drawing_stack.Push (dc);
			}

			return paint_event;
		}
Example #20
0
		// This method exists so controls overriding OnPaintBackground can have default background painting done
		internal virtual void PaintControlBackground (PaintEventArgs pevent) {

			bool tbstyle_flat = ((CreateParams.Style & (int) ToolBarStyles.TBSTYLE_FLAT) != 0);

			// If we have transparent background
			if (((BackColor.A != 0xff) && GetStyle(ControlStyles.SupportsTransparentBackColor)) || tbstyle_flat) {
				if (parent != null) {
					PaintEventArgs	parent_pe;
					GraphicsState	state;

					parent_pe = new PaintEventArgs(pevent.Graphics, new Rectangle(pevent.ClipRectangle.X + Left, pevent.ClipRectangle.Y + Top, pevent.ClipRectangle.Width, pevent.ClipRectangle.Height));

					state = parent_pe.Graphics.Save();
					parent_pe.Graphics.TranslateTransform(-Left, -Top);
					parent.OnPaintBackground(parent_pe);
					parent_pe.Graphics.Restore(state);

					state = parent_pe.Graphics.Save();
					parent_pe.Graphics.TranslateTransform(-Left, -Top);
					parent.OnPaint(parent_pe);
					parent_pe.Graphics.Restore(state);
					parent_pe.SetGraphics(null);
				}
			}

			if ((clip_region != null) && (XplatUI.UserClipWontExposeParent)) {
				if (parent != null) {
					PaintEventArgs	parent_pe;
					Region		region;
					GraphicsState	state;
					Hwnd		hwnd;

					hwnd = Hwnd.ObjectFromHandle(Handle);

					if (hwnd != null) {
						parent_pe = new PaintEventArgs(pevent.Graphics, new Rectangle(pevent.ClipRectangle.X + Left, pevent.ClipRectangle.Y + Top, pevent.ClipRectangle.Width, pevent.ClipRectangle.Height));

						region = new Region ();
						region.MakeEmpty();
						region.Union(ClientRectangle);

						foreach (Rectangle r in hwnd.ClipRectangles) {
							region.Union (r);
						}

						state = parent_pe.Graphics.Save();
						parent_pe.Graphics.Clip = region;

						parent_pe.Graphics.TranslateTransform(-Left, -Top);
						parent.OnPaintBackground(parent_pe);
						parent_pe.Graphics.Restore(state);

						state = parent_pe.Graphics.Save();
						parent_pe.Graphics.Clip = region;

						parent_pe.Graphics.TranslateTransform(-Left, -Top);
						parent.OnPaint(parent_pe);
						parent_pe.Graphics.Restore(state);
						parent_pe.SetGraphics(null);

						region.Intersect(clip_region);
						pevent.Graphics.Clip = region;
					}
				}
			}

			if (background_image == null) {
				if (!tbstyle_flat) {
					Rectangle paintRect = pevent.ClipRectangle;
					Brush pen = ThemeEngine.Current.ResPool.GetSolidBrush(BackColor);
					pevent.Graphics.FillRectangle(pen, paintRect);
				}
				return;
			}

			DrawBackgroundImage (pevent.Graphics);
		}
 /// <summary>
 /// Makes the current <see cref="RichTextBoxLineNumbers"/> transparent
 /// by matching <see cref="Region"/> to the given <see cref="GraphicsPath"/>s.
 /// </summary>
 /// <param name="graphicPaths"></param>
 private void MakeTransparent(IEnumerable<GraphicsPath> graphicPaths)
 {
   var region = new Region(ClientRectangle);
   region.MakeEmpty();
   foreach (var path in graphicPaths)
     region.Union(path);
   Region = region;
 }
        void FillRegionEmpty(Graphics g)
        {
            Pen myPen = new Pen(Color.FromArgb(196, 0xC3, 0xC9, 0xCF), (float)0.6);
            SolidBrush myBrush = new SolidBrush(Color.FromArgb(127, 0xDD, 0xDD, 0xF0));

            // Create the first rectangle and draw it to the screen in myPen color.
            g.DrawRectangle(myPen, regionRect1);

            // Create a region using the first rectangle.
            Region myRegion = new Region(regionRect1);
            myRegion.MakeEmpty ();

            // Fill the region which basically clears the screen to the background color.
            // Take a look at the initialize method of DrawingView.
            // This may set the rectangle to Black depending on the context
            // passed.  On a NSView set WantsLayers and the Layer Background color.
            g.FillRegion(myBrush, myRegion);

            title = "FillEmptyRegion";
        }
        void FillRegionEmptyXor(Graphics g)
        {
            Pen myPen = new Pen(Color.FromArgb(196, 0xC3, 0xC9, 0xCF), (float)0.6);
            SolidBrush myBrush = new SolidBrush(Color.FromArgb(127, 0xDD, 0xDD, 0xF0));

            // Create the first rectangle and draw it to the screen in black.
            g.DrawRectangle(myPen, regionRect1);
            g.FillRectangle(myBrush, regionRect1);

            myPen.Color = Color.FromArgb(196, 0xF9, 0xBE, 0xA6);
            myBrush.Color = Color.FromArgb(127, 0xFF, 0xE0, 0xE0);

            // create the second rectangle and draw it to the screen in red.
            g.DrawRectangle(myPen,
                            Rectangle.Round(regionRectF2));
            g.FillRectangle(myBrush, regionRect2);

            // Create a region using the first rectangle.
            Region myRegion = new Region();
            myRegion.MakeEmpty();

            // Get the area of intersection for myRegion when combined with
            // complementRect.
            myRegion.Xor(regionRectF2);

            myBrush.Color = Color.FromArgb(127, 0x66, 0xEF, 0x7F);
            myPen.Color = Color.FromArgb(255, 0, 0x33, 0);

            g.FillRegion(myBrush, myRegion);

            title = "FillRegionEmptyXor";
        }
		void OnMouseLeave (object sender, EventArgs e)
		{
			Region region_to_invalidate = new Region ();
			region_to_invalidate.MakeEmpty ();
			bool dirty = false;
			if (ThemeEngine.Current.ScrollBarHasHoverArrowButtonStyle) {
				region_to_invalidate.Union (first_arrow_area);
				region_to_invalidate.Union (second_arrow_area);
				dirty = true;
			} else
				if (ThemeEngine.Current.ScrollBarHasHotElementStyles)
					if (first_button_entered) {
						region_to_invalidate.Union (first_arrow_area);
						dirty = true;
					} else if (second_button_entered) {
						region_to_invalidate.Union (second_arrow_area);
						dirty = true;
					}
			if (ThemeEngine.Current.ScrollBarHasHotElementStyles)
				if (thumb_entered) {
					region_to_invalidate.Union (thumb_pos);
					dirty = true;
				}
			first_button_entered = false;
			second_button_entered = false;
			thumb_entered = false;
			if (dirty)
				Invalidate (region_to_invalidate);
			region_to_invalidate.Dispose ();
		}
 public Region getAffectedRegion()
 {
     Region region = new Region();
     region.MakeEmpty();
     //region.Union(Bounds);
     foreach( SignalConnector conn in connectionsIn )
         region.Union(conn.getRegion());
     foreach( SignalConnector conn in connectionsOut )
         region.Union(conn.getRegion());
     return region;
 }
Example #26
0
        /// <summary>
        /// OnPaint will go through the enabled elements (vertical ReminderMessage, GridLines, LineNumbers, BorderLines, MarginLines) and will
        /// draw them if enabled. At the same time, it will build GraphicsPaths for each of those elements (that are enabled), which will be used 
        /// in SeeThroughMode (if it's active): the figures in the GraphicsPaths will form a customized outline for the control by setting them as the 
        /// Region of the LineNumber control. Note: the vertical ReminderMessages are only drawn during designtime. 
        /// </summary>
        /// <param name="e"></param>
        /// <remarks></remarks>
        protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        {
            //   Build the list of visible LineNumberItems (= zLNIs) first. (doesn't take long, so it can stay in OnPaint)
            this.Update_VisibleLineNumberItems();
            base.OnPaint(e);

            // --- QualitySettings
            if (zLineNumbers_AntiAlias == true) {
                e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
            } else {
                e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SystemDefault;
            }

            // --- Local Declarations
            string zTextToShow = "";
            string zReminderToShow = "";
            StringFormat zSF = new StringFormat();
            SizeF zTextSize = default(SizeF);
            Pen zPen = new Pen(this.ForeColor);
            SolidBrush zBrush = new SolidBrush(this.ForeColor);
            Point zPoint = new Point(0, 0);
            Rectangle zItemClipRectangle = new Rectangle(0, 0, 0, 0);

            //   NOTE: The GraphicsPaths are only used for SeeThroughMode
            //   FillMode.Winding: combined outline ( Alternate: XOR'ed outline )
            System.Drawing.Drawing2D.GraphicsPath zGP_GridLines = new System.Drawing.Drawing2D.GraphicsPath(System.Drawing.Drawing2D.FillMode.Winding);
            System.Drawing.Drawing2D.GraphicsPath zGP_BorderLines = new System.Drawing.Drawing2D.GraphicsPath(System.Drawing.Drawing2D.FillMode.Winding);
            System.Drawing.Drawing2D.GraphicsPath zGP_MarginLines = new System.Drawing.Drawing2D.GraphicsPath(System.Drawing.Drawing2D.FillMode.Winding);
            System.Drawing.Drawing2D.GraphicsPath zGP_LineNumbers = new System.Drawing.Drawing2D.GraphicsPath(System.Drawing.Drawing2D.FillMode.Winding);
            Region zRegion = new Region(base.ClientRectangle);

            // ----------------------------------------------
            // --- DESIGNTIME / NO VISIBLE ITEMS
            if (this.DesignMode == true) {
                //   Show a vertical reminder message
                if (zParent == null) {
                    zReminderToShow = "-!- Set ParentRichTextBox -!-";
                } else {
                    if (zLNIs.Count == 0)
                        zReminderToShow = "LineNrs (  " + zParent.Name + "  )";
                }
                if (zReminderToShow.Length > 0) {
                    // --- Centering and Rotation for the reminder message
                    e.Graphics.TranslateTransform(this.Width / 2, this.Height / 2);
                    e.Graphics.RotateTransform(-90);
                    zSF.Alignment = StringAlignment.Center;
                    zSF.LineAlignment = StringAlignment.Center;
                    // --- Show the reminder message (with small shadow)
                    zTextSize = e.Graphics.MeasureString(zReminderToShow, this.Font, zPoint, zSF);
                    e.Graphics.DrawString(zReminderToShow, this.Font, Brushes.WhiteSmoke, 1, 1, zSF);
                    e.Graphics.DrawString(zReminderToShow, this.Font, Brushes.Firebrick, 0, 0, zSF);
                    e.Graphics.ResetTransform();

                    //Rectangle zReminderRectangle = new Rectangle(this.Width / 2 - zTextSize.Height / 2, this.Height / 2 - zTextSize.Width / 2, zTextSize.Height, zTextSize.Width);
                    Rectangle zReminderRectangle = new Rectangle((int)(this.Width / 2 - zTextSize.Height / 2), (int)(this.Height / 2 - zTextSize.Width / 2), (int)(zTextSize.Height), (int)(zTextSize.Width));
                    zGP_LineNumbers.AddRectangle(zReminderRectangle);
                    zGP_LineNumbers.CloseFigure();

                    if (zAutoSizing == true) {
                        zReminderRectangle.Inflate((int)(zTextSize.Height * 0.2), (int)(zTextSize.Width * 0.1));
                        //zReminderRectangle.Inflate(zTextSize.Height * 0.2, zTextSize.Width * 0.1);
                        zAutoSizing_Size = new Size(zReminderRectangle.Width, zReminderRectangle.Height);
                    }
                }
            }

            // ----------------------------------------------
            // --- DESIGN OR RUNTIME / WITH VISIBLE ITEMS (which means zParent exists)
            if (zLNIs.Count > 0) {
                //   The visible LineNumberItems with their BackgroundGradient and GridLines
                //   Loop through every visible LineNumberItem
                System.Drawing.Drawing2D.LinearGradientBrush zLGB = null;
                zPen = new Pen(zGridLines_Color, zGridLines_Thickness);
                zPen.DashStyle = zGridLines_Style;
                zSF.Alignment = StringAlignment.Near;
                zSF.LineAlignment = StringAlignment.Near;
                //zSF.FormatFlags = StringFormatFlags.FitBlackBox + StringFormatFlags.NoClip + StringFormatFlags.NoWrap;
                zSF.FormatFlags = StringFormatFlags.FitBlackBox | StringFormatFlags.NoClip | StringFormatFlags.NoWrap;

                for (int zA = 0; zA <= zLNIs.Count - 1; zA++) {
                    // --- BackgroundGradient
                    if (zGradient_Show == true) {
                        //zLGB = new Drawing2D.LinearGradientBrush(zLNIs(zA).Rectangle, zGradient_StartColor, zGradient_EndColor, zGradient_Direction);
                        zLGB = new System.Drawing.Drawing2D.LinearGradientBrush(zLNIs[zA].Rectangle, zGradient_StartColor, zGradient_EndColor, zGradient_Direction);
                        e.Graphics.FillRectangle(zLGB, zLNIs[zA].Rectangle);
                        //e.Graphics.FillRectangle(zLGB, zLNIs(zA).Rectangle);
                    }

                    // --- GridLines
                    if (zGridLines_Show == true) {
                        e.Graphics.DrawLine(zPen, new Point(0, zLNIs[zA].Rectangle.Y), new Point(this.Width, zLNIs[zA].Rectangle.Y));
                        //e.Graphics.DrawLine(zPen, new Point(0, zLNIs(zA).Rectangle.Y), new Point(this.Width, zLNIs(zA).Rectangle.Y));

                        //   NOTE: Every item in a GraphicsPath is a closed figure, so instead of adding gridlines as lines, we'll add them
                        //   as rectangles that loop out of sight. Their height uses the zContentRectangle which is the maxsize of
                        //   the ParentRichTextBox's contents.
                        //   NOTE: Slight adjustment needed when the first item has a negative Y coordinate.
                        //   This explains the " - zLNIs(0).Rectangle.Y" (which adds the negative size to the height
                        //   to make sure the rectangle's bottompart stays out of sight)
                        //zGP_GridLines.AddRectangle(new Rectangle(-zGridLines_Thickness, zLNIs(zA).Rectangle.Y, this.Width + zGridLines_Thickness * 2, this.Height - zLNIs(0).Rectangle.Y + zGridLines_Thickness));
                        zGP_GridLines.AddRectangle(new Rectangle(	(int)(-zGridLines_Thickness),
                                                                                                            (int)(zLNIs[zA].Rectangle.Y),
                                                                                                            (int)(this.Width + zGridLines_Thickness * 2),
                                                                                                            (int)(this.Height - zLNIs[zA].Rectangle.Y + zGridLines_Thickness)
                                                                                                            ));
                        zGP_GridLines.CloseFigure();
                    }

                    // --- LineNumbers
                    if (zLineNumbers_Show == true) {
                        //   TextFormatting
                        if (zLineNumbers_ShowLeadingZeroes == true) {
                            zTextToShow = (zLineNumbers_ShowAsHexadecimal ? zLNIs[zA].LineNumber.ToString("X") : zLNIs[zA].LineNumber.ToString(zLineNumbers_Format));
                            //zTextToShow = (zLineNumbers_ShowAsHexadecimal ? zLNIs(zA).LineNumber.ToString("X") : zLNIs(zA).LineNumber.ToString(zLineNumbers_Format));
                        } else {
                            zTextToShow = (zLineNumbers_ShowAsHexadecimal ? zLNIs[zA].LineNumber.ToString("X") : zLNIs[zA].LineNumber.ToString());
                            //zTextToShow = (zLineNumbers_ShowAsHexadecimal ? zLNIs(zA).LineNumber.ToString("X") : zLNIs(zA).LineNumber.ToString);
                        }

                        //   TextSizing
                        zTextSize = e.Graphics.MeasureString(zTextToShow, this.Font, zPoint, zSF);
                        //   TextAlignment and positioning   (zPoint = TopLeftCornerPoint of the text)
                        //   TextAlignment, padding, manual offset (via LineNrs_Offset) and zTextSize are all included in the calculation of zPoint.
                        switch (zLineNumbers_Alignment) {
                            case ContentAlignment.TopLeft:
                                zPoint = new Point((int)(zLNIs[zA].Rectangle.Left + this.Padding.Left + zLineNumbers_Offset.Width), (int)(zLNIs[zA].Rectangle.Top + this.Padding.Top + zLineNumbers_Offset.Height));
                                break;
                            case ContentAlignment.MiddleLeft:
                                zPoint = new Point((int)(zLNIs[zA].Rectangle.Left + this.Padding.Left + zLineNumbers_Offset.Width), (int)(zLNIs[zA].Rectangle.Top + (zLNIs[zA].Rectangle.Height / 2) + zLineNumbers_Offset.Height - zTextSize.Height / 2));
                                break;
                            case ContentAlignment.BottomLeft:
                                zPoint = new Point((int)(zLNIs[zA].Rectangle.Left + this.Padding.Left + zLineNumbers_Offset.Width), (int)(zLNIs[zA].Rectangle.Bottom - this.Padding.Bottom + 1 + zLineNumbers_Offset.Height - zTextSize.Height));
                                break;
                            case ContentAlignment.TopCenter:
                                zPoint = new Point((int)(zLNIs[zA].Rectangle.Width / 2 + zLineNumbers_Offset.Width - zTextSize.Width / 2), (int)(zLNIs[zA].Rectangle.Top + this.Padding.Top + zLineNumbers_Offset.Height));
                                break;
                            case ContentAlignment.MiddleCenter:
                                zPoint = new Point((int)(zLNIs[zA].Rectangle.Width / 2 + zLineNumbers_Offset.Width - zTextSize.Width / 2), (int)(zLNIs[zA].Rectangle.Top + (zLNIs[zA].Rectangle.Height / 2) + zLineNumbers_Offset.Height - zTextSize.Height / 2));
                                break;
                            case ContentAlignment.BottomCenter:
                                zPoint = new Point((int)(zLNIs[zA].Rectangle.Width / 2 + zLineNumbers_Offset.Width - zTextSize.Width / 2), (int)(zLNIs[zA].Rectangle.Bottom - this.Padding.Bottom + 1 + zLineNumbers_Offset.Height - zTextSize.Height));
                                break;
                            case ContentAlignment.TopRight:
                                zPoint = new Point((int)(zLNIs[zA].Rectangle.Right - this.Padding.Right + zLineNumbers_Offset.Width - zTextSize.Width), (int)(zLNIs[zA].Rectangle.Top + this.Padding.Top + zLineNumbers_Offset.Height));
                                break;
                            case ContentAlignment.MiddleRight:
                                zPoint = new Point((int)(zLNIs[zA].Rectangle.Right - this.Padding.Right + zLineNumbers_Offset.Width - zTextSize.Width), (int)(zLNIs[zA].Rectangle.Top + (zLNIs[zA].Rectangle.Height / 2) + zLineNumbers_Offset.Height - zTextSize.Height / 2));
                                break;
                            case ContentAlignment.BottomRight:
                                zPoint = new Point((int)(zLNIs[zA].Rectangle.Right - this.Padding.Right + zLineNumbers_Offset.Width - zTextSize.Width), (int)(zLNIs[zA].Rectangle.Bottom - this.Padding.Bottom + 1 + zLineNumbers_Offset.Height - zTextSize.Height));
                                break;
                        }
                        //   TextClipping
                        zItemClipRectangle = new Rectangle(zPoint, zTextSize.ToSize());
                        if (zLineNumbers_ClipByItemRectangle == true) {
                            //   If selected, the text will be clipped so that it doesn't spill out of its own LineNumberItem-area.
                            //   Only the part of the text inside the LineNumberItem.Rectangle should be visible, so intersect with the ItemRectangle
                            //   The SetClip method temporary restricts the drawing area of the control for whatever is drawn next.
                            zItemClipRectangle.Intersect(zLNIs[zA].Rectangle);
                            e.Graphics.SetClip(zItemClipRectangle);
                        }
                        //   TextDrawing
                        e.Graphics.DrawString(zTextToShow, this.Font, zBrush, zPoint, zSF);
                        e.Graphics.ResetClip();
                        //   The GraphicsPath for the LineNumber is just a rectangle behind the text, to keep the paintingspeed high and avoid ugly artifacts.
                        zGP_LineNumbers.AddRectangle(zItemClipRectangle);
                        zGP_LineNumbers.CloseFigure();
                    }
                }

                // --- GridLinesThickness and Linestyle in SeeThroughMode. All GraphicsPath lines are drawn as solid to keep the paintingspeed high.
                if (zGridLines_Show == true) {
                    zPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
                    zGP_GridLines.Widen(zPen);
                }

                // --- Memory CleanUp
                if (zLGB != null)
                    zLGB.Dispose();
            }

            // ----------------------------------------------
            // --- DESIGN OR RUNTIME / ALWAYS
            //Point zP_Left = new Point(Math.Floor(zBorderLines_Thickness / 2), Math.Floor(zBorderLines_Thickness / 2));
            //Point zP_Right = new Point(this.Width - Math.Ceiling(zBorderLines_Thickness / 2), this.Height - Math.Ceiling(zBorderLines_Thickness / 2));

            Point zP_Left = new Point(
                                                                    (int)(Math.Floor(zBorderLines_Thickness / 2)),
                                                                    (int)(Math.Floor(zBorderLines_Thickness / 2))
                                                             );
            Point zP_Right = new Point(
                                                                    (int)(this.Width - Math.Ceiling(zBorderLines_Thickness / 2)),
                                                                    (int)(this.Height - Math.Ceiling(zBorderLines_Thickness / 2))
                                                                );

            // --- BorderLines
            Point[] zBorderLines_Points = {
                new Point(zP_Left.X, zP_Left.Y),
                new Point(zP_Right.X, zP_Left.Y),
                new Point(zP_Right.X, zP_Right.Y),
                new Point(zP_Left.X, zP_Right.Y),
                new Point(zP_Left.X, zP_Left.Y)
            };
            if (zBorderLines_Show == true) {
                zPen = new Pen(zBorderLines_Color, zBorderLines_Thickness);
                zPen.DashStyle = zBorderLines_Style;
                e.Graphics.DrawLines(zPen, zBorderLines_Points);
                zGP_BorderLines.AddLines(zBorderLines_Points);
                zGP_BorderLines.CloseFigure();
                //   BorderThickness and Style for SeeThroughMode
                zPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
                zGP_BorderLines.Widen(zPen);
            }

            // --- MarginLines
            if (zMarginLines_Show == true && zMarginLines_Side > LineNumberDockSide.None) {
                zP_Left = new Point((int)(-zMarginLines_Thickness), (int)(-zMarginLines_Thickness));
                zP_Right = new Point((int)(this.Width + zMarginLines_Thickness), (int)(this.Height + zMarginLines_Thickness));
                zPen = new Pen(zMarginLines_Color, zMarginLines_Thickness);
                zPen.DashStyle = zMarginLines_Style;
                if (zMarginLines_Side == LineNumberDockSide.Left | zMarginLines_Side == LineNumberDockSide.Height) {
                    e.Graphics.DrawLine(zPen, new Point(
                                                                                            (int)(Math.Floor(zMarginLines_Thickness / 2)), 0),
                                                                                            new Point(
                                                                                                                (int)(Math.Floor(zMarginLines_Thickness / 2)),
                                                                                                                this.Height - 1)
                                                                                                                );
                    zP_Left = new Point(
                                                            (int)(Math.Ceiling(zMarginLines_Thickness / 2)),
                                                            (int)(-zMarginLines_Thickness));
                }
                if (zMarginLines_Side == LineNumberDockSide.Right | zMarginLines_Side == LineNumberDockSide.Height) {
                    e.Graphics.DrawLine(zPen, new Point(
                                                                                            (int)(this.Width - Math.Ceiling(zMarginLines_Thickness / 2)), 0),
                                                                                            new Point(
                                                                                                                (int)(this.Width - Math.Ceiling(zMarginLines_Thickness / 2)),
                                                                                                                (int)(this.Height - 1))
                                                                                        );

                    zP_Right = new Point(
                                                                (int)(this.Width - Math.Ceiling(zMarginLines_Thickness / 2)),
                                                                (int)(this.Height + zMarginLines_Thickness)
                                                            );
                }
                //   GraphicsPath for the MarginLines(s):
                //   MarginLines(s) are drawn as a rectangle connecting the zP_Left and zP_Right points, which are either inside or
                //   outside of sight, depending on whether the MarginLines at that side is visible. zP_Left: TopLeft and ZP_Right: BottomRight
                zGP_MarginLines.AddRectangle(new Rectangle(zP_Left, new Size(zP_Right.X - zP_Left.X, zP_Right.Y - zP_Left.Y)));
                zPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
                zGP_MarginLines.Widen(zPen);
            }

            // ----------------------------------------------
            // --- SeeThroughMode
            //   combine all the GraphicsPaths (= zGP_... ) and set them as the region for the control.
            if (zSeeThroughMode == true) {
                zRegion.MakeEmpty();
                zRegion.Union(zGP_BorderLines);
                zRegion.Union(zGP_MarginLines);
                zRegion.Union(zGP_GridLines);
                zRegion.Union(zGP_LineNumbers);
            }

            // --- Region
            if (zRegion.GetBounds(e.Graphics).IsEmpty == true) {
                //   Note: If the control is in a condition that would show it as empty, then a border-region is still drawn regardless of it's borders on/off state.
                //   This is added to make sure that the bounds of the control are never lost (it would remain empty if this was not done).
                zGP_BorderLines.AddLines(zBorderLines_Points);
                zGP_BorderLines.CloseFigure();
                zPen = new Pen(zBorderLines_Color, 1);
                zPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
                zGP_BorderLines.Widen(zPen);

                zRegion = new Region(zGP_BorderLines);
            }
            this.Region = zRegion;

            // ----------------------------------------------
            // --- Memory CleanUp
            if (zPen != null)
                zPen.Dispose();
            if (zBrush != null)
                zPen.Dispose();
            if (zRegion != null)
                zRegion.Dispose();
            if (zGP_GridLines != null)
                zGP_GridLines.Dispose();
            if (zGP_BorderLines != null)
                zGP_BorderLines.Dispose();
            if (zGP_MarginLines != null)
                zGP_MarginLines.Dispose();
            if (zGP_LineNumbers != null)
                zGP_LineNumbers.Dispose();
        }
Example #27
0
        /// <summary>
        /// Given a control returns the region of the control, also it returs the region of the control 
        /// that is not obscured by another window.
        /// </summary>
        /// <param name="ctrl">The sources control.</param>
        /// <param name="controlRegion">The region of the control.</param>
        /// <param name="notObscuredControlRegion">The region not obscured by another windows.</param>
        private static void GetVisibilityRegionsForControl(Control ctrl, out Region controlRegion, out Region notObscuredControlRegion)
        {
            Control parentInternal = null;
            Control parentInternalParent = null;

            if (!ctrl.IsHandleCreated || !ctrl.Visible)
            {
                controlRegion = new Region();
                controlRegion.MakeEmpty();
                notObscuredControlRegion = new Region();
                notObscuredControlRegion.MakeEmpty();
                return;
            }

            RECT rect = new RECT();
            parentInternal = ctrl.GetType().GetProperty("ParentInternal", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(ctrl, null) as Control;
            if (parentInternal != null)
            {
                parentInternalParent = parentInternal.GetType().GetProperty("ParentInternal", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(parentInternal, null) as Control;
                while (parentInternalParent != null)
                {
                    parentInternal = parentInternalParent;
                    parentInternalParent = parentInternal.GetType().GetProperty("ParentInternal", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(parentInternal, null) as Control;
                }
            }
            GetWindowRect(new HandleRef(ctrl, ctrl.Handle), ref rect);
            controlRegion = new Region(Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom));
            notObscuredControlRegion = new Region(Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom));

            IntPtr ptr2;
            IntPtr handle;
            if (parentInternal != null)
                handle = parentInternal.Handle;
            else
                handle = ctrl.Handle;

            for (IntPtr ptr = handle; (ptr2 = GetWindow(new HandleRef(null, ptr), 3)) != IntPtr.Zero; ptr = ptr2)
            {
                GetWindowRect(new HandleRef(null, ptr2), ref rect);
                Rectangle rectangle = Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom);
                if (IsWindowVisible(new HandleRef(null, ptr2)))
                {
                    notObscuredControlRegion.Exclude(rectangle);
                }
            }
        }
    CreateClippedDrawingObjects()
    {
        AssertValid();

        Graphics oGraphics = this.CreateGraphics();
        Region oRegion = new Region();
        oRegion.MakeEmpty();
        oGraphics.Clip = oRegion;

        // Use an arbitrary height, which none of the drawing methods pay
        // attention to.  If a non-zero width is available, use it.  (The width
        // is zero when the control is being resized as it is first shown.)

        Int32 iWidth = this.ClientRectangle.Width;

        Rectangle oControlRectangle = new Rectangle(0, 0,
            iWidth == 0 ? 100 : iWidth, 100);

        return ( CreateDrawingObjects(oGraphics, oControlRectangle) );
    }
 internal static void TakeWorkflowSnapShot(WorkflowView workflowView, ViewPortData viewPortData)
 {
     Bitmap memoryBitmap = viewPortData.MemoryBitmap;
     using (Graphics graphics = Graphics.FromImage(memoryBitmap))
     {
         graphics.SmoothingMode = SmoothingMode.HighQuality;
         graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
         using (PaintEventArgs args = new PaintEventArgs(graphics, viewPortData.LogicalViewPort))
         {
             workflowView.ActiveLayout.OnPaint(args, viewPortData);
         }
         Matrix matrix = new Matrix();
         matrix.Scale(viewPortData.Scaling.Width, viewPortData.Scaling.Height, MatrixOrder.Prepend);
         Point[] pts = new Point[] { viewPortData.LogicalViewPort.Location };
         matrix.TransformPoints(pts);
         matrix.Translate((float) (-pts[0].X + viewPortData.ShadowDepth.Width), (float) (-pts[0].Y + viewPortData.ShadowDepth.Height), MatrixOrder.Append);
         graphics.Transform = matrix;
         if (workflowView.RootDesigner != null)
         {
             using (Region region = new Region())
             {
                 using (GraphicsPath path = ActivityDesignerPaint.GetDesignerPath(workflowView.RootDesigner, false))
                 {
                     Region clip = graphics.Clip;
                     region.MakeEmpty();
                     region.Union(path);
                     graphics.Clip = region;
                     AmbientTheme ambientTheme = WorkflowTheme.CurrentTheme.AmbientTheme;
                     graphics.FillRectangle(ambientTheme.BackgroundBrush, workflowView.RootDesigner.Bounds);
                     if (ambientTheme.ShowGrid)
                     {
                         ActivityDesignerPaint.DrawGrid(graphics, workflowView.RootDesigner.Bounds);
                     }
                     graphics.Clip = clip;
                     try
                     {
                         using (PaintEventArgs args2 = new PaintEventArgs(graphics, viewPortData.LogicalViewPort))
                         {
                             ((IWorkflowDesignerMessageSink) workflowView.RootDesigner).OnPaint(args2, viewPortData.LogicalViewPort);
                         }
                     }
                     catch (Exception)
                     {
                     }
                 }
             }
         }
         using (PaintEventArgs args3 = new PaintEventArgs(graphics, workflowView.RootDesigner.Bounds))
         {
             using (WorkflowMessageDispatchData data = new WorkflowMessageDispatchData(workflowView, EventArgs.Empty))
             {
                 foreach (WorkflowDesignerMessageFilter filter in data.Filters)
                 {
                     try
                     {
                         if (((IWorkflowDesignerMessageSink) filter).OnPaint(args3, viewPortData.LogicalViewPort))
                         {
                             goto Label_0230;
                         }
                     }
                     catch (Exception)
                     {
                     }
                 }
             }
         }
     Label_0230:
         graphics.Transform = new Matrix();
         if (!viewPortData.ShadowDepth.IsEmpty)
         {
             Bitmap image = new Bitmap(memoryBitmap);
             using (Brush brush = new SolidBrush(Color.FromArgb(220, Color.White)))
             {
                 graphics.FillRectangle(brush, new Rectangle(Point.Empty, new Size((memoryBitmap.Size.Width - viewPortData.ShadowDepth.Width) - 1, (memoryBitmap.Size.Height - viewPortData.ShadowDepth.Height) - 1)));
             }
             ImageAttributes imageAttr = new ImageAttributes();
             imageAttr.SetColorKey(viewPortData.TransparentColor, viewPortData.TransparentColor, ColorAdjustType.Default);
             imageAttr.SetColorKey(viewPortData.TransparentColor, viewPortData.TransparentColor, ColorAdjustType.Bitmap);
             graphics.DrawImage(image, new Rectangle(-viewPortData.ShadowDepth.Width, -viewPortData.ShadowDepth.Height, memoryBitmap.Width, memoryBitmap.Height), 0, 0, memoryBitmap.Width, memoryBitmap.Height, GraphicsUnit.Pixel, imageAttr);
             image.Dispose();
         }
     }
 }
Example #30
0
		/// <summary>Returns new Region object for given ElementStyle.</summary>
		/// <returns>New instance of Region object.</returns>
		/// <param name="e">Information to describe ElementStyle.</param>
		public static Region GetStyleRegion(ElementStyleDisplayInfo e)
		{
            Rectangle rectPath = e.Bounds;
            if (e.Style.PaintBorder && e.Style.CornerType!=eCornerType.Square)
            {
                rectPath.Width--;
                rectPath.Height--;
            }

            GraphicsPath path = ElementStyleDisplay.GetBackgroundPath(e.Style, rectPath);
            Region r = new Region();
            r.MakeEmpty();
            r.Union(path);
            // Widen path for the border...
            if (e.Style.PaintBorder && (e.Style.CornerType == eCornerType.Rounded || e.Style.CornerType == eCornerType.Diagonal || 
                e.Style.CornerTypeTopLeft == eCornerType.Rounded || e.Style.CornerTypeTopLeft == eCornerType.Diagonal ||
                e.Style.CornerTypeTopRight==eCornerType.Rounded || e.Style.CornerTypeTopRight==eCornerType.Diagonal ||
                e.Style.CornerTypeBottomLeft==eCornerType.Rounded || e.Style.CornerTypeBottomLeft==eCornerType.Diagonal ||
                e.Style.CornerTypeBottomRight==eCornerType.Rounded || e.Style.CornerTypeBottomRight==eCornerType.Diagonal))
            {
                using (Pen pen = new Pen(Color.Black, (e.Style.BorderTopWidth>0?e.Style.BorderTopWidth:1)))
                {
                    path.Widen(pen);
                }
                //Region r2 = new Region(path);
                r.Union(path);
            }

            return r;
            //GraphicsPath path=ElementStyleDisplay.GetBackgroundPath(e.Style,e.Bounds,false);
            //return new Region(path);
		}
Example #31
0
		internal override PaintEventArgs PaintEventStart(ref Message msg, IntPtr handle, bool client)
		{
			PaintEventArgs	paint_event;
			Hwnd		hwnd;
			Hwnd		paint_hwnd;
			
			// 
			// handle  (and paint_hwnd) refers to the window that is should be painted.
			// msg.HWnd (and hwnd) refers to the window that got the paint message.
			// 
			
			hwnd = Hwnd.ObjectFromHandle(msg.HWnd);
			if (msg.HWnd == handle) {
				paint_hwnd = hwnd;
			} else {
				paint_hwnd = Hwnd.ObjectFromHandle (handle);
			}
	
			if (Caret.Visible == true) {
				Caret.Paused = true;
				HideCaret();
			}

			Graphics dc;

			if (client) {
				dc = Graphics.FromHwnd (paint_hwnd.client_window);

				Region clip_region = new Region ();
				clip_region.MakeEmpty();

				foreach (Rectangle r in hwnd.ClipRectangles) {
					/* Expand the region slightly.
					 * See bug 464464.
					 */
					Rectangle r2 = Rectangle.FromLTRB (r.Left, r.Top, r.Right, r.Bottom + 1);
					clip_region.Union (r2);
				}

				if (hwnd.UserClip != null) {
					clip_region.Intersect(hwnd.UserClip);
				}

				dc.Clip = clip_region;
				paint_event = new PaintEventArgs(dc, hwnd.Invalid);
				hwnd.expose_pending = false;

				hwnd.ClearInvalidArea();

				hwnd.drawing_stack.Push (paint_event);
				hwnd.drawing_stack.Push (dc);

				return paint_event;
			} else {
				dc = Graphics.FromHwnd (paint_hwnd.whole_window);

				if (!hwnd.nc_invalid.IsEmpty) {
					dc.SetClip (hwnd.nc_invalid);
					paint_event = new PaintEventArgs(dc, hwnd.nc_invalid);
				} else {
					paint_event = new PaintEventArgs(dc, new Rectangle(0, 0, hwnd.width, hwnd.height));
				}
				hwnd.nc_expose_pending = false;

				hwnd.ClearNcInvalidArea ();

				hwnd.drawing_stack.Push (paint_event);
				hwnd.drawing_stack.Push (dc);

				return paint_event;
			}
		}
Example #32
0
    ///////////////////////////////////////////////////////////////////////////////
    // Eventhandler                                                              //
    ///////////////////////////////////////////////////////////////////////////////
    #region EVENTS

    ///////////////////////////////////////////////////////////////////////////////
    // Eventhandler for UI, Menu, Buttons, Toolbars etc.                         //
    ///////////////////////////////////////////////////////////////////////////////
    #region WINDOWSEVENTHANDLER
    #endregion //WINDOWSEVENTHANDLER

    ///////////////////////////////////////////////////////////////////////////////
    // Eventhandler for Custom Defined Events                                    //
    ///////////////////////////////////////////////////////////////////////////////
    #region CUSTOMEVENTHANDLER
    #endregion //CUSTOMEVENTHANDLER

    #endregion //EVENTS

    ///////////////////////////////////////////////////////////////////////////////
    // Methods and Eventhandling for Background tasks                            //
    ///////////////////////////////////////////////////////////////////////////////
    #region BACKGROUNDWORKER
    #endregion //BACKGROUNDWORKER

    ///////////////////////////////////////////////////////////////////////////////
    // Inherited methods                                                         //
    ///////////////////////////////////////////////////////////////////////////////
    #region OVERRIDES

    /// <summary>
    /// Overridden <see cref="VGElement.Draw(Graphics)"/>.  
    /// Draws the ellipse to the given graphics context.
    /// </summary>
    /// <param name="graphics">Graphics context to draw to</param>
    /// <exception cref="ArgumentNullException">Thrown, when graphics object is null.</exception>
    public override void Draw(Graphics graphics)
    {
      if (graphics == null)
      {
        throw new ArgumentNullException("Graphics object should not be null.");
      }

      if ((ShapeDrawAction & ShapeDrawAction.Fill) == ShapeDrawAction.Fill)
      {
        if (this.Brush != null)
        {
          if (this.inverted)
          {
            Region drawRegion = new Region();
            drawRegion.MakeEmpty();
            drawRegion.Union(graphics.Clip);
            drawRegion.Exclude(this.region);
            graphics.FillRegion(this.Brush, drawRegion);
          }
          else
          {
            graphics.FillRegion(this.Brush, this.region);
          }
        }
      }

      // Draw name and selection frame if applicable
      base.Draw(graphics);
    }