public override void Draw(System.Drawing.RectangleF dirtyRect)
        {
            var g = new Graphics();

            // NSView does not have a background color so we just use Clear to white here
            g.Clear(Color.White);

            //RectangleF ClientRectangle = this.Bounds;
            RectangleF ClientRectangle = dirtyRect;

            // Calculate the location and size of the drawing area
            // within which we want to draw the graphics:
            Rectangle rect = new Rectangle((int)ClientRectangle.X, (int)ClientRectangle.Y,
                                           (int)ClientRectangle.Width, (int)ClientRectangle.Height);
            drawingRectangle = new Rectangle(rect.Location, rect.Size);
            drawingRectangle.Inflate(-offset, -offset);
            //Draw ClientRectangle and drawingRectangle using Pen:
            g.DrawRectangle(Pens.Red, rect);
            g.DrawRectangle(Pens.Black, drawingRectangle);
            // Draw a line from point (3,2) to Point (6, 7)
            // using the Pen with a width of 3 pixels:
            Pen aPen = new Pen(Color.Green, 3);
            g.DrawLine(aPen, Point2D(new PointF(3, 2)),
                       Point2D(new PointF(6, 7)));

            g.PageUnit = GraphicsUnit.Inch;
            ClientRectangle = new RectangleF(0.5f,0.5f, 1.5f, 1.5f);
            aPen.Width = 1 / g.DpiX;
            g.DrawRectangle(aPen, ClientRectangle);

            aPen.Dispose();

            g.Dispose();
        }
Пример #2
2
        public override void Apply(Graphics graphics, Bitmap applyBitmap, Rectangle rect, RenderMode renderMode)
        {
            Rectangle applyRect = ImageHelper.CreateIntersectRectangle(applyBitmap.Size, rect, Invert);

            if (applyRect.Width == 0 || applyRect.Height == 0)
            {
                // nothing to do
                return;
            }
            GraphicsState state = graphics.Save();
            if (Invert)
            {
                graphics.SetClip(applyRect);
                graphics.ExcludeClip(rect);
            }
            ColorMatrix grayscaleMatrix = new ColorMatrix(new[] {
                new[] {.3f, .3f, .3f, 0, 0},
                new[] {.59f, .59f, .59f, 0, 0},
                new[] {.11f, .11f, .11f, 0, 0},
                new float[] {0, 0, 0, 1, 0},
                new float[] {0, 0, 0, 0, 1}
            });
            using (ImageAttributes ia = new ImageAttributes())
            {
                ia.SetColorMatrix(grayscaleMatrix);
                graphics.DrawImage(applyBitmap, applyRect, applyRect.X, applyRect.Y, applyRect.Width, applyRect.Height, GraphicsUnit.Pixel, ia);
            }
            graphics.Restore(state);
        }
Пример #3
1
 public PortLinkGlyph(string id, Rectangle bounds)
     : base(id)
 {
     _From = bounds.Location;
     _To = new Point (bounds.X + bounds.Width, bounds.Y + bounds.Height);
     BuildContactPoints ();
 }
Пример #4
1
		/// <summary></summary>
		/// <param name="box"></param>
		/// <param name="g"></param>
		protected override void PaintThisProgress(Rectangle box, Graphics g) {
			try {
				box.Width -= 1;
				box.Height -= 1;
			} catch {}
			if (box.Width <= 1) {
				return;
			}

			g.FillRectangle(brush, box);
			Rectangle innerBox = box;
			innerBox.Inflate(-1, -1);
			g.DrawRectangle(inner, innerBox);
			g.DrawLine(outer, box.X, box.Y, box.Right, box.Y);
			g.DrawLine(outer, box.X, box.Y, box.X, box.Bottom);
			g.DrawLine(edge, box.X, box.Bottom, box.Right, box.Bottom);

			if (gloss != null) {
				gloss.PaintGloss(box, g);
			}

			if (showEdge) {
				g.DrawLine(edge, box.Right, box.Y, box.Right, box.Bottom);
			}
		}
Пример #5
1
		private Rectangle GetThemedRect(Rectangle r)
		{
			const int offset=6;

			switch(m_Tab.Parent.TabAlignment)
			{
				case eTabStripAlignment.Top:
				{
					r.Y-=offset;
					r.Height+=offset;
					break;
				}
				case eTabStripAlignment.Left:
				{
					r.X-=offset;
					r.Width+=offset;
					break;
				}
				case eTabStripAlignment.Right:
				{
					r.Width+=offset;
					break;
				}
				case eTabStripAlignment.Bottom:
				{
					r.Height+=offset;
					break;
				}
					
			}
			return r;
		}
Пример #6
1
        private Bitmap DrawDropImage(int size)
        {
            Bitmap bmp = new Bitmap(size, size);
            Rectangle rect = new Rectangle(0, 0, size, size);

            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.FillRectangle(Brushes.CornflowerBlue, rect);

                g.DrawRectangleProper(Pens.Black, rect);

                using (Pen pen = new Pen(Color.WhiteSmoke, 5) { Alignment = PenAlignment.Inset })
                {
                    g.DrawRectangleProper(pen, rect.Offset(-1));
                }

                string text = Resources.DropForm_DrawDropImage_Drop_here;

                using (Font font = new Font("Arial", 20, FontStyle.Bold))
                using (StringFormat sf = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center })
                {
                    g.DrawString(text, font, Brushes.Black, rect.LocationOffset(1), sf);
                    g.DrawString(text, font, Brushes.White, rect, sf);
                }
            }

            return bmp;
        }
Пример #7
1
        public static void CalcDifference(Bitmap bmp1, Bitmap bmp2)
        {
            PixelFormat pxf = PixelFormat.Format32bppArgb;
            Rectangle rect = new Rectangle(0, 0, bmp1.Width, bmp1.Height);

            BitmapData bmpData1 = bmp1.LockBits(rect, ImageLockMode.ReadWrite, pxf);
            IntPtr ptr1 = bmpData1.Scan0;

            BitmapData bmpData2 = bmp2.LockBits(rect, ImageLockMode.ReadOnly, pxf);
            IntPtr ptr2 = bmpData2.Scan0;

            int numBytes = bmp1.Width * bmp1.Height * bytesPerPixel;
            byte[] pixels1 = new byte[numBytes];
            byte[] pixels2 = new byte[numBytes];

            System.Runtime.InteropServices.Marshal.Copy(ptr1, pixels1, 0, numBytes);
            System.Runtime.InteropServices.Marshal.Copy(ptr2, pixels2, 0, numBytes);

            for (int i = 0; i < numBytes; i += bytesPerPixel)
            {
                if (pixels1[i + 0] == pixels2[i + 0] &&
                    pixels1[i + 1] == pixels2[i + 1] &&
                    pixels1[i + 2] == pixels2[i + 2])
                {
                    pixels1[i + 0] = 255;
                    pixels1[i + 1] = 255;
                    pixels1[i + 2] = 255;
                    pixels1[i + 3] = 0;
                }
            }

            System.Runtime.InteropServices.Marshal.Copy(pixels1, 0, ptr1, numBytes);
            bmp1.UnlockBits(bmpData1);
            bmp2.UnlockBits(bmpData2);
        }
        protected override void OnSizeChanged(EventArgs e)
        {
			base.OnSizeChanged(e);

            boxOffset = Height / 2 - 9;
            boxRectangle = new Rectangle(boxOffset, boxOffset, CHECKBOX_SIZE - 1, CHECKBOX_SIZE - 1);
        }
Пример #9
1
        void DrawGraphics(Object sender, PaintEventArgs PaintNow)
        {
            Rectangle Dot = new Rectangle(SpriteX, SpriteY, SpriteWidth, SpriteHeight); // Create rectangle (start position, and size X & Y)
            SolidBrush WhiteBrush = new SolidBrush(Color.White); // Create Brush(Color) to paint rectangle

            PaintNow.Graphics.FillRectangle(WhiteBrush, Dot);
        }
Пример #10
1
 public static Rectangle RtlTransform(Control control, Rectangle rectangle)
 {
     if (control.RightToLeft != RightToLeft.Yes)
         return rectangle;
     else
         return new Rectangle(control.ClientRectangle.Right - rectangle.Right, rectangle.Y, rectangle.Width, rectangle.Height);
 }
Пример #11
1
 public Bitmap DrawBitmap(int theight, int twidth)
 {
     Bitmap bitmap3;
     Bitmap bitmap = new Bitmap(this.Width, this.Height);
     Rectangle targetBounds = new Rectangle(0, 0, this.Width, this.Height);
     this.MyBrowser.DrawToBitmap(bitmap, targetBounds);
     Image image = bitmap;
     Bitmap bitmap2 = new Bitmap(twidth, theight, image.PixelFormat);
     Graphics graphics = Graphics.FromImage(bitmap2);
     graphics.CompositingQuality = CompositingQuality.HighSpeed;
     graphics.SmoothingMode = SmoothingMode.HighSpeed;
     graphics.InterpolationMode = InterpolationMode.HighQualityBilinear;
     Rectangle rect = new Rectangle(0, 0, twidth, theight);
     graphics.DrawImage(image, rect);
     try
     {
         bitmap3 = bitmap2;
     }
     catch
     {
         bitmap3 = null;
     }
     finally
     {
         image.Dispose();
         image = null;
         this.MyBrowser.Dispose();
         this.MyBrowser = null;
     }
     return bitmap3;
 }
Пример #12
1
        public unsafe Point GetNextPoint(Rectangle rectTrack, byte* pIn, Size sizeIn, double[] Qu, double[] PuY0)
        {
            double[] w = new double[256];//方向权值
            for (int i = 0; i < 256; i++)
            {
                w[i] = Math.Sqrt(Qu[i] / PuY0[i]);
            }

            PointF center = new PointF(
                (float)rectTrack.Left + (float)rectTrack.Width / 2,
                (float)rectTrack.Top + (float)rectTrack.Height / 2);
            SizeF H = new SizeF((float)rectTrack.Width / 2, (float)rectTrack.Height / 2);
            double numeratorX = 0, numeratorY = 0;//分子
            double denominatorX = 0, denominatorY = 0;//分母
            for (int y = rectTrack.Top; y < rectTrack.Bottom; y++)
            {
                for (int x = rectTrack.Left; x < rectTrack.Right; x++)
                {
                    int index = DataManager.GetIndex(x, y, sizeIn.Width);
                    byte u = pIn[index];
                    //计算以高斯分布为核函数自变量X的值
                    double X = ((Math.Pow((x - center.X), 2) + Math.Pow((y - center.Y), 2))
                            / (Math.Pow(H.Width, 2) + Math.Pow(H.Height, 2)));
                    //负的高斯分布核函数的值
                    double Gi = -Math.Exp(-Math.Pow(X, 2) / 2) / Math.Sqrt(2 * Math.PI);

                    numeratorX += x * w[u] * Gi;
                    numeratorY += y * w[u] * Gi;
                    denominatorX += w[u] * Gi;
                    denominatorY += w[u] * Gi;
                }
            }
            return new Point((int)(numeratorX / denominatorX), (int)(numeratorY / denominatorY));
        }
Пример #13
1
 public void Apply(Surface dst, Surface src, Rectangle[] rois, int startIndex, int length)
 {
     for (int i = startIndex; i < startIndex + length; ++i)
     {
         ApplyBase(dst, rois[i].Location, src, rois[i].Location, rois[i].Size);
     }
 }
		protected virtual void SetLocation()
		{
			TextArea textArea = control.ActiveTextAreaControl.TextArea;
			TextLocation caretPos  = textArea.Caret.Position;
			
			int xpos = textArea.TextView.GetDrawingXPos(caretPos.Y, caretPos.X);
			int rulerHeight = textArea.TextEditorProperties.ShowHorizontalRuler ? textArea.TextView.FontHeight : 0;
			Point pos = new Point(textArea.TextView.DrawingPosition.X + xpos,
			                      textArea.TextView.DrawingPosition.Y + (textArea.Document.GetVisibleLine(caretPos.Y)) * textArea.TextView.FontHeight
			                      - textArea.TextView.TextArea.VirtualTop.Y + textArea.TextView.FontHeight + rulerHeight);
			
			Point location = control.ActiveTextAreaControl.PointToScreen(pos);
			
			// set bounds
			Rectangle bounds = new Rectangle(location, drawingSize);
			
			if (!workingScreen.Contains(bounds)) {
				if (bounds.Right > workingScreen.Right) {
					bounds.X = workingScreen.Right - bounds.Width;
				}
				if (bounds.Left < workingScreen.Left) {
					bounds.X = workingScreen.Left;
				}
				if (bounds.Top < workingScreen.Top) {
					bounds.Y = workingScreen.Top;
				}
				if (bounds.Bottom > workingScreen.Bottom) {
					bounds.Y = bounds.Y - bounds.Height - control.ActiveTextAreaControl.TextArea.TextView.FontHeight;
					if (bounds.Bottom > workingScreen.Bottom) {
						bounds.Y = workingScreen.Bottom - bounds.Height;
					}
				}
			}
			Bounds = bounds;
		}
		public RECT(Rectangle rect) 
		{
			Left = rect.Left; 
			Top = rect.Top;
			Right = rect.Right;
			Bottom = rect.Bottom;
		}
 /// <summary>
 /// Initialize a new instance of the ButtonDragRectangleEventArgs class.
 /// </summary>
 /// <param name="point">Left mouse down point.</param>
 public ButtonDragRectangleEventArgs(Point point)
 {
     _point = point;
     _dragRect = new Rectangle(_point, Size.Empty);
     _dragRect.Inflate(SystemInformation.DragSize);
     _preDragOffset = true;
 }
Пример #17
1
        public override void DrawAppointment(Graphics g, Rectangle rect, Appointment appointment, bool isSelected, Rectangle gripRect, bool enableShadows, bool useroundedCorners)
        {
            if (appointment == null)
                throw new ArgumentNullException("appointment");

            if (g == null)
                throw new ArgumentNullException("g");

            if (rect.Width != 0 && rect.Height != 0)
                using (StringFormat format = new StringFormat())
                {
                    format.Alignment = StringAlignment.Near;
                    format.LineAlignment = StringAlignment.Near;

                    if ((appointment.Locked) && isSelected)
                    {
                        // Draw back
                        using (Brush m_Brush = new System.Drawing.Drawing2D.HatchBrush(System.Drawing.Drawing2D.HatchStyle.Wave, Color.LightGray, appointment.Color))
                            g.FillRectangle(m_Brush, rect);
                    }
                    else
                    {
                        // Draw back
                        using (SolidBrush m_Brush = new SolidBrush(appointment.Color))
                            g.FillRectangle(m_Brush, rect);
                    }

                    if (isSelected)
                    {
                        using (Pen m_Pen = new Pen(appointment.BorderColor, 4))
                            g.DrawRectangle(m_Pen, rect);

                        Rectangle m_BorderRectangle = rect;

                        m_BorderRectangle.Inflate(2, 2);

                        using (Pen m_Pen = new Pen(SystemColors.WindowFrame, 1))
                            g.DrawRectangle(m_Pen, m_BorderRectangle);

                        m_BorderRectangle.Inflate(-4, -4);

                        using (Pen m_Pen = new Pen(SystemColors.WindowFrame, 1))
                            g.DrawRectangle(m_Pen, m_BorderRectangle);
                    }
                    else
                    {
                        // Draw gripper
                        gripRect.Width += 1;

                        using (SolidBrush m_Brush = new SolidBrush(appointment.BorderColor))
                            g.FillRectangle(m_Brush, gripRect);

                        using (Pen m_Pen = new Pen(SystemColors.WindowFrame, 1))
                            g.DrawRectangle(m_Pen, rect);
                    }

                    rect.X += gripRect.Width;
                    g.DrawString(appointment.Subject, this.BaseFont, SystemBrushes.WindowText, rect, format);
                }
        }
Пример #18
1
 protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates elementState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
 {
     var buttonRectangle = new Rectangle(cellBounds.X + 2, cellBounds.Y + 2, cellBounds.Width - 4, cellBounds.Height - 4);
     base.Paint(graphics, clipBounds, buttonRectangle, rowIndex, elementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
     var imageRectangle = new Rectangle(cellBounds.X + 6, cellBounds.Y + 6, _detailImage.Width, _detailImage.Height);
     graphics.DrawImage(_detailImage, imageRectangle);
 }
Пример #19
1
        static long CalculateActorSelectionPriority(ActorInfo info, Rectangle bounds, int2 selectionPixel)
        {
            var centerPixel = new int2(bounds.X, bounds.Y);
            var pixelDistance = (centerPixel - selectionPixel).Length;

            return ((long)-pixelDistance << 32) + info.SelectionPriority();
        }
Пример #20
1
    /// <summary>
    /// Returns the position closest to the given position such that this
    /// form will be completely on the screen.  E.g., if the form would be
    /// cropped off the right side of the screen, the returned point would
    /// have the same Y position and a lesser X position such that the right
    /// side of the form would be flush with the right side of the screen if
    /// it were placed at the given position.
    /// </summary>
    private Point CorrectPosition(Point position) {
      Point newPosition = new Point(position.X, position.Y);

      // Figure out the bounds of all screens (we just round if the monitors
      // happen to be different sizes).
      Rectangle screenBounds = Screen.FromControl(this).WorkingArea;
      int left = screenBounds.Left;
      int top = screenBounds.Top;
      int right = screenBounds.Right;
      int bottom = screenBounds.Bottom;
      foreach (Screen screen in Screen.AllScreens) {
        left = Math.Min(screen.WorkingArea.Left, left);
        top = Math.Min(screen.WorkingArea.Top, top);
        right = Math.Max(screen.WorkingArea.Right, right);
        bottom = Math.Max(screen.WorkingArea.Bottom, bottom);
      }
      Rectangle workingBounds = new Rectangle(left, top, right - left, bottom - top);

      Rectangle formBounds = this.Bounds;
      if (newPosition.X < workingBounds.Left) {
        newPosition.X = workingBounds.Left;
      } else if (newPosition.X + formBounds.Width > workingBounds.Right) {
        newPosition.X = workingBounds.Right - formBounds.Width;
      }
      if (newPosition.Y < workingBounds.Top) {
        newPosition.Y = workingBounds.Top;
      } else if (newPosition.Y + formBounds.Height > workingBounds.Bottom) {
        newPosition.Y = workingBounds.Bottom - formBounds.Height;
      }
      return newPosition;
    }
		protected override void OnMouseDown(MouseEventArgs e)
		{
			// get the index of the clicked item
			_rowIndexFromMouseDown = HitTest(e.X, e.Y).RowIndex;

			// basic mouse handling has right clicks show context menu without changing selection, so we handle it manually here
			if (e.Button == MouseButtons.Right)
				HandleRightMouseDown(e);

			// call the base class, so that the row gets selected, etc.
			base.OnMouseDown(e);

			if (_rowIndexFromMouseDown > -1)
			{
				// Remember the point where the mouse down occurred. 
				// The DragSize indicates the size that the mouse can move 
				// before a drag event should be started.                
				Size dragSize = SystemInformation.DragSize;

				// Create a rectangle using the DragSize, with the mouse position being
				// at the center of the rectangle.
				_dragBoxFromMouseDown = new Rectangle(new Point(e.X - (dragSize.Width/2), e.Y - (dragSize.Height/2)), dragSize);
			}
			else
			{
				// Reset the rectangle if the mouse is not over an item in the ListBox.
				_dragBoxFromMouseDown = Rectangle.Empty;
			}
		}
        // 描画
        private unsafe void xnDraw()
        {
            // カメライメージの更新を待ち、画像データを取得する
              context.WaitOneUpdateAll(image);
              ImageMetaData imageMD = image.GetMetaData();

              // カメラ画像の作成
              lock (this) {
            // 書き込み用のビットマップデータを作成
            Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
            BitmapData data = bitmap.LockBits(rect, ImageLockMode.WriteOnly,
                        System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            // 生データへのポインタを取得
            byte* dst = (byte*)data.Scan0.ToPointer();
            byte* src = (byte*)image.ImageMapPtr.ToPointer();

            for (int i = 0; i < imageMD.DataSize; i += 3, src += 3, dst += 3) {
              dst[0] = src[2];
              dst[1] = src[1];
              dst[2] = src[0];
            }

            bitmap.UnlockBits(data);
              }

              // 現在の状態を表示する
              Graphics g = Graphics.FromImage(bitmap);
              string message = "Gesture:" + gestures[gestureIndex] +
                      ", Status:" + gestureStatus.ToString() + "\n";
              g.DrawString(message, font, brush, point);
        }
Пример #23
0
        public static Rectangle AdaptProportionalRect(
            Rectangle rectMax,
            int nRealWidth,
            int nRealHeight,
            bool fillOut)
        {
            int nWidth;
            int nHeight;

            if (rectMax.Width < 1 || rectMax.Height < 1 || nRealHeight < 1 || nRealHeight < 1)
                return Rectangle.Empty;

            var sMaxRatio = (decimal)rectMax.Width / rectMax.Height;
            var sRealRatio = (decimal)nRealWidth / nRealHeight;

            if ((sMaxRatio < sRealRatio) ^ fillOut)
            {
                nWidth = Math.Min(rectMax.Width, nRealWidth);
                nHeight = (int)(nWidth / sRealRatio);
            }
            else
            {
                nHeight = Math.Min(rectMax.Height, nRealHeight);
                nWidth = (int)(nHeight * sRealRatio);
            }

            return new Rectangle(
                rectMax.X + (rectMax.Width - nWidth) / 2,
                rectMax.Y + (rectMax.Height - nHeight) / 2,
                nWidth,
                nHeight);
        }
Пример #24
0
 //This constructor is passed the bounds this form is to show in
 //It is used when in normal mode
 public MainForm(Rectangle Bounds)
 {
     InitializeComponent();
         this.Bounds = Bounds;
         //hide the cursor
         Cursor.Hide();
 }
Пример #25
0
        public static GraphicsPath GetRoundedCornerTab(GraphicsPath graphicsPath, Rectangle rect, bool upCorner)
        {
            if (graphicsPath == null)
                graphicsPath = new GraphicsPath();
            else
                graphicsPath.Reset();
            
            int curveSize = 6;
            if (upCorner)
            {
                graphicsPath.AddLine(rect.Left, rect.Bottom, rect.Left, rect.Top + curveSize / 2);
                graphicsPath.AddArc(new Rectangle(rect.Left, rect.Top, curveSize, curveSize), 180, 90);
                graphicsPath.AddLine(rect.Left + curveSize / 2, rect.Top, rect.Right - curveSize / 2, rect.Top);
                graphicsPath.AddArc(new Rectangle(rect.Right - curveSize, rect.Top, curveSize, curveSize), -90, 90);
                graphicsPath.AddLine(rect.Right, rect.Top + curveSize / 2, rect.Right, rect.Bottom);
            }
            else
            {
                graphicsPath.AddLine(rect.Right, rect.Top, rect.Right, rect.Bottom - curveSize / 2);
                graphicsPath.AddArc(new Rectangle(rect.Right - curveSize, rect.Bottom - curveSize, curveSize, curveSize), 0, 90);
                graphicsPath.AddLine(rect.Right - curveSize / 2, rect.Bottom, rect.Left + curveSize / 2, rect.Bottom);
                graphicsPath.AddArc(new Rectangle(rect.Left, rect.Bottom - curveSize, curveSize, curveSize), 90, 90);
                graphicsPath.AddLine(rect.Left, rect.Bottom - curveSize / 2, rect.Left, rect.Top);
            }

            return graphicsPath;
        }
Пример #26
0
 private void CalcFinalSizes()
 {
     Size textSize = GetTextSize();
     var width = 2 * SPACING + textSize.Width;
     var height = 2 * SPACING + textSize.Height + 6;
     if (width > MAX_SIZE.Width)
     {
         width = MAX_SIZE.Width;
     }
     else if (width < MIN_SIZE.Width)
     {
         width = MIN_SIZE.Width;
     }
     if (height > MAX_SIZE.Height)
     {
         height = MAX_SIZE.Height;
     }
     else if (height < MIN_SIZE.Height)
     {
         height = MIN_SIZE.Height;
     }
     this.Size = new Size(width, height);
     var textWidth = Math.Min(this.Width - 2 * SPACING, textSize.Width);
     var textHeight = Math.Min(this.Height - 2 * SPACING, textSize.Height);
     var textLeft = (this.Width - textWidth) / 2;
     var textTop = (this.Height - textHeight - 6) / 2;
     this.textRect = new Rectangle(textLeft, textTop, textWidth, textHeight);
 }
 private static Point RandomPoint(Random rng, Rectangle bounds)
 {
     return new Point(
         rng.Next(bounds.Left, bounds.Right),
         rng.Next(bounds.Top, bounds.Bottom)
     );
 }
Пример #28
0
        protected override void OnDrawItem( DrawItemEventArgs e )
        {
            base.OnDrawItem( e );

            if ( e.Index != -1 )
            {
                object item = Items[e.Index];
                e.DrawBackground();
                e.DrawFocusRectangle();

                bool separator = item is SeparatorItem;

                Rectangle bounds = e.Bounds;
                bool drawSeparator = separator && ( e.State & DrawItemState.ComboBoxEdit ) != DrawItemState.ComboBoxEdit;
                if ( drawSeparator )
                {
                    bounds.Height -= separatorHeight;
                }

                TextRenderer.DrawText( e.Graphics, GetDisplayText( e.Index ), Font, bounds, e.ForeColor, e.BackColor, TextFormatFlags.Left | TextFormatFlags.VerticalCenter );

                if ( drawSeparator )
                {
                    Rectangle sepRect = new Rectangle( e.Bounds.Left, e.Bounds.Bottom - separatorHeight, e.Bounds.Width, separatorHeight );
                    using ( Brush b = new SolidBrush( BackColor ) )
                    {
                        e.Graphics.FillRectangle( b, sepRect );
                    }
                    e.Graphics.DrawLine( SystemPens.ControlText, sepRect.Left + 2, sepRect.Top + 1, sepRect.Right - 2, sepRect.Top + 1 );
                }
            }
        }
 public ToolStripItemGlyph(ToolStripItem item, ToolStripItemDesigner itemDesigner, Rectangle bounds, System.Windows.Forms.Design.Behavior.Behavior b)
     : base(bounds, Cursors.Default, item, b)
 {
     this._item = item;
     this._bounds = bounds;
     this._itemDesigner = itemDesigner;
 }
Пример #30
0
        protected override void Edit(CurrencyManager source, int rowNum, Rectangle bounds, bool readOnly,	string instantText, bool cellIsVisible)
        {
            if (isEditing)
                return;

            if (cellIsVisible)
            {
                mSel.Bounds = new Rectangle(bounds.X + 2, bounds.Y + 2, bounds.Width, bounds.Height);
                mSel.Visible = true;
                mSel.OnControlChanged += new EventHandler(OpenDateValueChanged);
                object value = base.GetColumnValueAtRow( source, rowNum );
                if ( value == null )
                    mSel.pSelectedItem = new PlaceCode(0, 0);
                else
                    mSel.pSelectedItem = PlaceCode.PDC2PlaceCode(value.ToString());
                value = this.GetColumnValueAtRow( source, rowNum );
                if ( value == null )
                    mSel.pText = string.Empty;
                else
                    mSel.pText = value.ToString();
            }
            else
            {
                mSel.Visible = false;
            }

            if (mSel.Visible)
            {
                isEditing = true;
                base.ColumnStartedEditing(mSel);
                DataGridTableStyle.DataGrid.Invalidate(bounds);
            }
        }
Пример #31
0
        /// <summary>
        /// Paints a border around the image. If Image drop shadow is enabled,
        /// a shodow is drawn too.
        /// </summary>
        /// <param name="g">The graphics object</param>
        /// <param name="ImageRect">the rectangle region of the image</param>
        private void paint_ImageBorder(System.Drawing.Graphics g, System.Drawing.Rectangle ImageRect)
        {
            System.Drawing.Rectangle rect = ImageRect;

            //
            // If ImageDropShadow = true, draw shadow
            //
            if (ImageDropShadow)
            {
                System.Drawing.Pen p0 = new System.Drawing.Pen(System.Drawing.Color.FromArgb(80, 0, 0, 0));
                System.Drawing.Pen p1 = new System.Drawing.Pen(System.Drawing.Color.FromArgb(40, 0, 0, 0));
                g.DrawLine(p0, new Point(rect.Right, rect.Bottom), new Point(rect.Right + 1, rect.Bottom));
                g.DrawLine(p0, new Point(rect.Right + 1, rect.Top + 1), new Point(rect.Right + 1, rect.Bottom + 0));
                g.DrawLine(p1, new Point(rect.Right + 2, rect.Top + 2), new Point(rect.Right + 2, rect.Bottom + 1));
                g.DrawLine(p0, new Point(rect.Left + 1, rect.Bottom + 1), new Point(rect.Right + 0, rect.Bottom + 1));
                g.DrawLine(p1, new Point(rect.Left + 1, rect.Bottom + 2), new Point(rect.Right + 1, rect.Bottom + 2));
            }
            //
            // Draw Image Border
            //
            if (ImageBorderEnabled)
            {
                Color[] ColorArray         = null;
                float[] PositionArray      = null;
                System.Drawing.Color color = this.ImageBorderColor;
                if (!this.Enabled)
                {
                    color = System.Drawing.Color.LightGray;
                }
                //
                // initialize color and position array
                //
                ColorArray = new Color[] {
                    Blend(color, System.Drawing.Color.White, 40),
                    Blend(color, System.Drawing.Color.White, 20),
                    Blend(color, System.Drawing.Color.White, 30),
                    Blend(color, System.Drawing.Color.White, 00),
                    Blend(color, System.Drawing.Color.Black, 30),
                    Blend(color, System.Drawing.Color.Black, 70),
                };
                PositionArray = new float[] { 0.0f, .20f, .50f, .60f, .90f, 1.0f };
                //
                // create blend object
                //
                System.Drawing.Drawing2D.ColorBlend blend = new System.Drawing.Drawing2D.ColorBlend();
                blend.Colors    = ColorArray;
                blend.Positions = PositionArray;
                //
                // create brush and pens
                //
                using (var brush = new System.Drawing.Drawing2D.LinearGradientBrush(rect, BackColor,
                                                                                    Blend(BackColor, BackColor, 10), System.Drawing.Drawing2D.LinearGradientMode.Vertical))
                {
                    brush.InterpolationColors = blend;
                    using (var pen0 = new Pen(brush, 1))
                        using (var pen1 = new Pen(Color.Black))
                        {
                            //
                            // calculate points to draw line
                            //
                            rect.Inflate(1, 1);
                            var pts = border_Get(rect.Left, rect.Top, rect.Width, rect.Height);
                            border_Contract(1, ref pts);
                            //
                            // draw line 0
                            //
                            g.DrawLines(pen1, pts);
                            //
                            // draw line 1
                            //
                            border_Contract(1, ref pts);
                            g.DrawLines(pen0, pts);
                        }
                }
            }
        }
Пример #32
0
		public Region (Rectangle rect)                
		{
			Status status = GDIPlus.GdipCreateRegionRectI (ref rect, out nativeRegion);
			GDIPlus.CheckStatus (status);
		}
Пример #33
0
    public override int CaptureWithCursor(FrameInfo frame)
    {
        var res = new Result(-1);

        try
        {
            //Try to get the duplicated output frame within given time.
            res = DuplicatedOutput.TryAcquireNextFrame(0, out var info, out var resource);

            //Checks how to proceed with the capture. It could have failed, or the screen, cursor or both could have been captured.
            if (FrameCount == 0 && info.LastMouseUpdateTime == 0 && (res.Failure || resource == null))
            {
                //Somehow, it was not possible to retrieve the resource, frame or metadata.
                resource?.Dispose();
                return(FrameCount);
            }
            else if (FrameCount == 0 && info.TotalMetadataBufferSize == 0 && info.LastMouseUpdateTime > 0)
            {
                //Sometimes, the first frame has cursor info, but no screen changes.
                GetCursor(null, info, frame);
                resource?.Dispose();
                return(FrameCount);
            }

            #region Process changes

            //Something on screen was moved or changed.
            if (info.TotalMetadataBufferSize > 0)
            {
                //Copies the screen data into memory that can be accessed by the CPU.
                using (var screenTexture = resource.QueryInterface <Texture2D>())
                {
                    #region Moved rectangles

                    var movedRectangles = new OutputDuplicateMoveRectangle[info.TotalMetadataBufferSize];
                    DuplicatedOutput.GetFrameMoveRects(movedRectangles.Length, movedRectangles, out var movedRegionsLength);

                    for (var movedIndex = 0; movedIndex < movedRegionsLength / Marshal.SizeOf(typeof(OutputDuplicateMoveRectangle)); movedIndex++)
                    {
                        //Crop the destination rectangle to the screen area rectangle.
                        var left   = Math.Max(movedRectangles[movedIndex].DestinationRect.Left, Left - OffsetLeft);
                        var right  = Math.Min(movedRectangles[movedIndex].DestinationRect.Right, Left + Width - OffsetLeft);
                        var top    = Math.Max(movedRectangles[movedIndex].DestinationRect.Top, Top - OffsetTop);
                        var bottom = Math.Min(movedRectangles[movedIndex].DestinationRect.Bottom, Top + Height - OffsetTop);

                        //Copies from the screen texture only the area which the user wants to capture.
                        if (right > left && bottom > top)
                        {
                            //Limit the source rectangle to the available size within the destination rectangle.
                            var sourceWidth  = movedRectangles[movedIndex].SourcePoint.X + (right - left);
                            var sourceHeight = movedRectangles[movedIndex].SourcePoint.Y + (bottom - top);

                            Device.ImmediateContext.CopySubresourceRegion(screenTexture, 0,
                                                                          new ResourceRegion(movedRectangles[movedIndex].SourcePoint.X, movedRectangles[movedIndex].SourcePoint.Y, 0, sourceWidth, sourceHeight, 1),
                                                                          BackingTexture, 0, left - (Left - OffsetLeft), top - (Top - OffsetTop));
                        }
                    }

                    #endregion

                    #region Dirty rectangles

                    var dirtyRectangles = new RawRectangle[info.TotalMetadataBufferSize];
                    DuplicatedOutput.GetFrameDirtyRects(dirtyRectangles.Length, dirtyRectangles, out var dirtyRegionsLength);

                    for (var dirtyIndex = 0; dirtyIndex < dirtyRegionsLength / Marshal.SizeOf(typeof(RawRectangle)); dirtyIndex++)
                    {
                        //Crop screen positions and size to frame sizes.
                        var left   = Math.Max(dirtyRectangles[dirtyIndex].Left, Left - OffsetLeft);
                        var right  = Math.Min(dirtyRectangles[dirtyIndex].Right, Left + Width - OffsetLeft);
                        var top    = Math.Max(dirtyRectangles[dirtyIndex].Top, Top - OffsetTop);
                        var bottom = Math.Min(dirtyRectangles[dirtyIndex].Bottom, Top + Height - OffsetTop);

                        //Copies from the screen texture only the area which the user wants to capture.
                        if (right > left && bottom > top)
                        {
                            Device.ImmediateContext.CopySubresourceRegion(screenTexture, 0, new ResourceRegion(left, top, 0, right, bottom, 1), BackingTexture, 0, left - (Left - OffsetLeft), top - (Top - OffsetTop));
                        }
                    }

                    #endregion
                }
            }

            if (info.TotalMetadataBufferSize > 0 || info.LastMouseUpdateTime > 0)
            {
                //Copy the captured desktop texture into a staging texture, in order to show the mouse cursor and not make the captured texture dirty with it.
                Device.ImmediateContext.CopyResource(BackingTexture, StagingTexture);

                //Gets the cursor image and merges with the staging texture.
                GetCursor(StagingTexture, info, frame);
            }

            //Saves the most recent capture time.
            LastProcessTime = Math.Max(info.LastPresentTime, info.LastMouseUpdateTime);

            #endregion

            #region Gets the image data

            //Get the desktop capture texture.
            var data = Device.ImmediateContext.MapSubresource(StagingTexture, 0, MapMode.Read, MapFlags.None);

            if (data.IsEmpty)
            {
                Device.ImmediateContext.UnmapSubresource(StagingTexture, 0);
                resource?.Dispose();
                return(FrameCount);
            }

            var bitmap     = new System.Drawing.Bitmap(Width, Height, PixelFormat.Format32bppArgb);
            var boundsRect = new System.Drawing.Rectangle(0, 0, Width, Height);

            //Copy pixels from screen capture Texture to the GDI bitmap.
            var mapDest   = bitmap.LockBits(boundsRect, ImageLockMode.WriteOnly, bitmap.PixelFormat);
            var sourcePtr = data.DataPointer;
            var destPtr   = mapDest.Scan0;

            for (var y = 0; y < Height; y++)
            {
                //Copy a single line.
                Utilities.CopyMemory(destPtr, sourcePtr, Width * 4);

                //Advance pointers.
                sourcePtr = IntPtr.Add(sourcePtr, data.RowPitch);
                destPtr   = IntPtr.Add(destPtr, mapDest.Stride);
            }

            //Releases the source and dest locks.
            bitmap.UnlockBits(mapDest);

            //Set frame details.
            FrameCount++;
            frame.Path  = $"{Project.FullPath}{FrameCount}.png";
            frame.Delay = FrameRate.GetMilliseconds();
            frame.Image = bitmap;

            if (IsAcceptingFrames)
            {
                BlockingCollection.Add(frame);
            }

            #endregion

            Device.ImmediateContext?.UnmapSubresource(StagingTexture, 0);

            resource?.Dispose();
            return(FrameCount);
        }
        catch (SharpDXException se) when(se.ResultCode.Code == SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code)
        {
            return(FrameCount);
        }
        catch (SharpDXException se) when(se.ResultCode.Code == SharpDX.DXGI.ResultCode.DeviceRemoved.Result.Code || se.ResultCode.Code == SharpDX.DXGI.ResultCode.DeviceReset.Result.Code)
        {
            //When the device gets lost or reset, the resources should be instantiated again.
            DisposeInternal();
            Initialize();

            return(FrameCount);
        }
        catch (Exception ex)
        {
            LogWriter.Log(ex, "It was not possible to finish capturing the frame with DirectX.");

            MajorCrashHappened = true;

            if (IsAcceptingFrames)
            {
                Application.Current.Dispatcher.Invoke(() => OnError.Invoke(ex));
            }

            return(FrameCount);
        }
        finally
        {
            try
            {
                //Only release the frame if there was a success in capturing it.
                if (res.Success)
                {
                    DuplicatedOutput.ReleaseFrame();
                }
            }
            catch (Exception e)
            {
                LogWriter.Log(e, "It was not possible to release the frame.");
            }
        }
    }
Пример #34
0
 public CompressedImage GetScreenshot4(System.Drawing.Rectangle cropRect)
 {
     return(GetImage("7034b7a7-4116-47c5-b45e-bbee31b314cd", cropRect));
 }
Пример #35
0
 public CompressedImage GetScreenshot5(System.Drawing.Rectangle cropRect)
 {
     return(GetImage("e50ee231-8646-4b8f-8d46-43108f13dd74", cropRect));
 }
Пример #36
0
 public CompressedImage GetScreenshot7(System.Drawing.Rectangle cropRect)
 {
     return(GetImage("f7cf26d0-f616-4a2e-afc3-17f189cc8c09", cropRect));
 }
Пример #37
0
 //set variables to start tracking bool changes
 protected override void Edit(System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Rectangle bounds, bool readOnly, string instantText, bool cellIsVisible)
 {
     lockValue   = true;
     beingEdited = true;
     saveRow     = rowNum;
     saveValue   = (bool)base.GetColumnValueAtRow(source, rowNum);
     base.Edit(source, rowNum, bounds, readOnly, instantText, cellIsVisible);
 }
Пример #38
0
 /// ------------------------------------------------------------------------------------
 /// <summary>
 ///  Constructor 3
 /// </summary>
 /// <param name="g"></param>
 /// <param name="rect"></param>
 /// ------------------------------------------------------------------------------------
 public BorderDrawing(Graphics g, System.Drawing.Rectangle rect)
 {
     m_graphics = g;
     m_rect     = rect;
 }
Пример #39
0
        public override void Execute()
        {
            Bitmap                      MainWinImage;
            AutomationElement           targetWin = null;
            AutomationElement           gingerWin = null;
            List <System.Drawing.Point> result    = new List <System.Drawing.Point>();

            //System.Drawing.Point(0,0);
            if (!string.IsNullOrWhiteSpace(WindowName))
            {
                targetWin = UIAutomationGetWindowByTitle(WindowName);
            }

            string ExpectedImgFile1 = ExpectedImgFile;

            if (ExpectedImgFile1.StartsWith("~"))
            {
                string SolutionFolder1 = SolutionFolder.ToString();
                ExpectedImgFile1 = ExpectedImgFile1.Replace("~\\", "");
                ExpectedImgFile1 = System.IO.Path.Combine(SolutionFolder1, ExpectedImgFile1);
            }
            if (WindowName == "FULLSCREEN")
            {
                List <AutomationElement> wins = UIAutomationGetFirstLevelWindows();
                targetWin = AutomationElement.RootElement;

                foreach (AutomationElement w in wins)
                {
                    if (w == UIAutomationGetWindowByTitle("Amdocs Ginger Automation"))
                    {
                        gingerWin = w;
                        WinAPIAutomation.MinimizeWindow(w.Current.ProcessId);
                        break;
                    }
                }
                System.Drawing.Rectangle SelectionRectangle = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
                using (MainWinImage = new Bitmap(SelectionRectangle.Width, SelectionRectangle.Height))
                {
                    using (Graphics g = Graphics.FromImage(MainWinImage))
                    {
                        g.CopyFromScreen(new System.Drawing.Point(0, 0), System.Drawing.Point.Empty, SelectionRectangle.Size);
                    }

                    result = GetSubPositions(MainWinImage, Image.FromFile(ExpectedImgFile1));


                    if (result.Count <= 0)
                    {
                        this.Error = "Image is not found in the current window";
                        return;
                    }
                }
            }
            else if (string.IsNullOrWhiteSpace(WindowName) || targetWin == null)
            {
                List <AutomationElement> wins = UIAutomationGetFirstLevelWindows();
                targetWin = AutomationElement.RootElement;

                foreach (AutomationElement w in wins)
                {
                    if (w == UIAutomationGetWindowByTitle("Amdocs Ginger Automation"))
                    {
                        continue;
                    }
                    MainWinImage = GetWindowBitmap(w);
                    if (File.Exists(ExpectedImgFile1) && MainWinImage != null)
                    {
                        result = GetSubPositions(MainWinImage, Image.FromFile(ExpectedImgFile1));
                    }
                    else
                    {
                        continue;
                    }
                    if (result.Count > 0)
                    {
                        targetWin = w;
                        break;
                    }
                }

                if (result.Count <= 0)
                {
                    this.Error = "Image is not found in the current screen";
                    return;
                }
            }
            else
            {
                if (targetWin != null)
                {
                    WinAPIAutomation.ShowWindow(targetWin);
                    MainWinImage = GetWindowBitmap(targetWin);
                    result       = GetSubPositions(MainWinImage, Image.FromFile(ExpectedImgFile1));

                    if (result.Count <= 0)
                    {
                        this.Error = "Image is not found in the current window";
                        return;
                    }
                }
                else
                {
                    this.Error = "The main searching is not existing";
                    return;
                }
            }
        }
Пример #40
0
        /// <summary>
        /// 4、绘制多个打印界面
        /// printDocument的PrintPage事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnPrintPage(object sender, PrintPageEventArgs e)
        {
            int leftMargin = Convert.ToInt32((e.MarginBounds.Left) * 3 / 4);   //左边距
            int topMargin  = Convert.ToInt32(e.MarginBounds.Top * 2 / 3);      //顶边距

            switch (StreamType)
            {
            case "txt":
                while (linesPrinted < lines.Length)
                {
                    //向画布中填写内容
                    e.Graphics.DrawString(lines[linesPrinted++], new Font("Arial", 10), Brushes.Black, leftMargin, topMargin, new StringFormat());

                    topMargin += 55;    //行高为55,可调整

                    //走纸换页
                    if (topMargin >= e.PageBounds.Height - 60)    //页面累加的高度大于页面高度。根据自己需要,可以适当调整
                    {
                        //如果大于设定的高
                        e.HasMorePages = true;

                        /*
                         * PrintPageEventArgs类的HaeMorePages属性为True时,通知控件器,必须再次調用OnPrintPage()方法,打印一个页面。
                         * PrintLoopI()有一个用於每个要打印的页面的序例。如果HasMorePages是False,PrintLoop()就会停止。
                         */
                        return;
                    }
                }

                break;

            case "image":    //一下涉及剪切图片,
                int width  = image.Width;
                int height = image.Height;
                if ((width / e.MarginBounds.Width) > (height / e.MarginBounds.Height))
                {
                    width  = e.MarginBounds.Width;
                    height = image.Height * e.MarginBounds.Width / image.Width;
                }
                else
                {
                    height = e.MarginBounds.Height;
                    width  = image.Width * e.MarginBounds.Height / image.Height;
                }

                System.Drawing.Rectangle destRect = new System.Drawing.Rectangle(topMargin, leftMargin, width, height);
                //向画布写入图片
                for (int i = 0; i < Convert.ToInt32(Math.Floor((double)image.Height / 820)) + 1; i++)
                {
                    e.Graphics.DrawImage(image, destRect, i * 820, i * 1170, image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel);
                    //走纸换页
                    if (i * 1170 >= e.PageBounds.Height - 60)    //页面累加的高度大于页面高度。根据自己需要,可以适当调整
                    {
                        //如果大于设定的高
                        e.HasMorePages = true;

                        /*
                         * PrintPageEventArgs类的HaeMorePages属性为True时,通知控件器,必须再次調用OnPrintPage()方法,打印一个页面。
                         * PrintLoopI()有一个用於每个要打印的页面的序例。如果HasMorePages是False,PrintLoop()就会停止。
                         */
                        return;
                    }
                }

                break;
            }

            //打印完毕后,画线条,且注明打印日期
            e.Graphics.DrawLine(new Pen(Color.Black), leftMargin, topMargin, e.MarginBounds.Right, topMargin);

            string strdatetime = DateTime.Now.ToLongDateString() + DateTime.Now.ToLongTimeString();

            e.Graphics.DrawString(string.Format("打印时间:{0}", strdatetime), mainFont, Brushes.Black, e.MarginBounds.Right - 240, topMargin + 40, new StringFormat());
            linesPrinted = 0;
            //绘制完成后,关闭多页打印功能
            e.HasMorePages = false;
        }
Пример #41
0
 public override void DrawDayBackground(System.Drawing.Graphics g, System.Drawing.Rectangle rect)
 {
 }
Пример #42
0
 public override void PositionEditingControl(bool setLocation, bool setSize, sd.Rectangle cellBounds, sd.Rectangle cellClip, swf.DataGridViewCellStyle cellStyle, bool singleVerticalBorderAdded, bool singleHorizontalBorderAdded, bool isFirstDisplayedColumn, bool isFirstDisplayedRow)
 {
     Handler.PositionEditingControl(RowIndex, ref cellClip, ref cellBounds);
     base.PositionEditingControl(setLocation, setSize, cellBounds, cellClip, cellStyle, singleVerticalBorderAdded, singleHorizontalBorderAdded, isFirstDisplayedColumn, isFirstDisplayedRow);
 }
Пример #43
0
 public RECT(System.Drawing.Rectangle r) : this(r.Left, r.Top, r.Right, r.Bottom)
 {
 }
Пример #44
0
    public override int ManualCapture(FrameInfo frame, bool showCursor = false)
    {
        var res = new Result(-1);

        try
        {
            //Try to get the duplicated output frame within given time.
            res = DuplicatedOutput.TryAcquireNextFrame(1000, out var info, out var resource);

            //Checks how to proceed with the capture. It could have failed, or the screen, cursor or both could have been captured.
            if (res.Failure || resource == null || (!showCursor && info.AccumulatedFrames == 0) || (showCursor && info.AccumulatedFrames == 0 && info.LastMouseUpdateTime <= LastProcessTime))
            {
                //Somehow, it was not possible to retrieve the resource, frame or metadata.
                //frame.WasDropped = true;
                //BlockingCollection.Add(frame);

                resource?.Dispose();
                return(FrameCount);
            }
            else if (showCursor && info.AccumulatedFrames == 0 && info.LastMouseUpdateTime > LastProcessTime)
            {
                //Gets the cursor shape if the screen hasn't changed in between, so the cursor will be available for the next frame.
                GetCursor(null, info, frame);

                resource.Dispose();
                return(FrameCount);
            }

            //Saves the most recent capture time.
            LastProcessTime = Math.Max(info.LastPresentTime, info.LastMouseUpdateTime);

            //Copy resource into memory that can be accessed by the CPU.
            using (var screenTexture = resource.QueryInterface <Texture2D>())
            {
                if (showCursor)
                {
                    //Copies from the screen texture only the area which the user wants to capture.
                    Device.ImmediateContext.CopySubresourceRegion(screenTexture, 0, new ResourceRegion(TrueLeft, TrueTop, 0, TrueRight, TrueBottom, 1), BackingTexture, 0);

                    //Copy the captured desktop texture into a staging texture, in order to show the mouse cursor and not make the captured texture dirty with it.
                    Device.ImmediateContext.CopyResource(BackingTexture, StagingTexture);

                    //Gets the cursor image and merges with the staging texture.
                    GetCursor(StagingTexture, info, frame);
                }
                else
                {
                    //Copies from the screen texture only the area which the user wants to capture.
                    Device.ImmediateContext.CopySubresourceRegion(screenTexture, 0, new ResourceRegion(TrueLeft, TrueTop, 0, TrueRight, TrueBottom, 1), StagingTexture, 0);
                }
            }

            //Get the desktop capture texture.
            var data = Device.ImmediateContext.MapSubresource(StagingTexture, 0, MapMode.Read, MapFlags.None);

            if (data.IsEmpty)
            {
                //frame.WasDropped = true;
                //BlockingCollection.Add(frame);

                Device.ImmediateContext.UnmapSubresource(StagingTexture, 0);
                resource.Dispose();
                return(FrameCount);
            }

            #region Get image data

            var bitmap     = new System.Drawing.Bitmap(Width, Height, PixelFormat.Format32bppArgb);
            var boundsRect = new System.Drawing.Rectangle(0, 0, Width, Height);

            //Copy pixels from screen capture Texture to the GDI bitmap.
            var mapDest   = bitmap.LockBits(boundsRect, ImageLockMode.WriteOnly, bitmap.PixelFormat);
            var sourcePtr = data.DataPointer;
            var destPtr   = mapDest.Scan0;

            for (var y = 0; y < Height; y++)
            {
                //Copy a single line.
                Utilities.CopyMemory(destPtr, sourcePtr, Width * 4);

                //Advance pointers.
                sourcePtr = IntPtr.Add(sourcePtr, data.RowPitch);
                destPtr   = IntPtr.Add(destPtr, mapDest.Stride);
            }

            //Release source and dest locks.
            bitmap.UnlockBits(mapDest);

            //Set frame details.
            FrameCount++;
            frame.Path  = $"{Project.FullPath}{FrameCount}.png";
            frame.Delay = FrameRate.GetMilliseconds();
            frame.Image = bitmap;
            BlockingCollection.Add(frame);

            #endregion

            Device.ImmediateContext.UnmapSubresource(StagingTexture, 0);

            resource.Dispose();
            return(FrameCount);
        }
        catch (SharpDXException se) when(se.ResultCode.Code == SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code)
        {
            return(FrameCount);
        }
        catch (SharpDXException se) when(se.ResultCode.Code == SharpDX.DXGI.ResultCode.DeviceRemoved.Result.Code || se.ResultCode.Code == SharpDX.DXGI.ResultCode.DeviceReset.Result.Code)
        {
            //When the device gets lost or reset, the resources should be instantiated again.
            DisposeInternal();
            Initialize();

            return(FrameCount);
        }
        catch (Exception ex)
        {
            LogWriter.Log(ex, "It was not possible to finish capturing the frame with DirectX.");

            MajorCrashHappened = true;
            OnError.Invoke(ex);
            return(FrameCount);
        }
        finally
        {
            try
            {
                //Only release the frame if there was a success in capturing it.
                if (res.Success)
                {
                    DuplicatedOutput.ReleaseFrame();
                }
            }
            catch (Exception e)
            {
                LogWriter.Log(e, "It was not possible to release the frame.");
            }
        }
    }
Пример #45
0
 public State Create(OverlayPlugin manager, XmlNode node, System.Drawing.Rectangle clip)
 {
     return(Create(manager, node));
 }
Пример #46
0
        /// <summary>
        /// This method paints the text and text shadow for the button.
        /// </summary>
        /// <param name="e">paint arguments use to paint the button</param>
        private void paint_Text(PaintEventArgs e)
        {
            if (e == null)
            {
                return;
            }
            if (e.Graphics == null)
            {
                return;
            }
            System.Drawing.Rectangle rect = GetTextDestinationRect();
            //
            // do offset if button is pushed
            //
            if ((State == BtnState.Pushed) && (OffsetPressedContent))
            {
                rect.Offset(1, 1);
            }
            //
            // caculate bounding rectagle for the text
            //
            System.Drawing.SizeF size = txt_Size(e.Graphics, this.Text, this.Font);
            //
            // calculate the starting location to paint the text
            //
            System.Drawing.Point pt = Calculate_LeftEdgeTopEdge(this.TextAlign, rect, (int)size.Width, (int)size.Height);
            //
            // If button state is inactive, paint the inactive text
            //
            if (State == BtnState.Inactive)
            {
                using (var solidBrush = new SolidBrush(DisabledTextColor))
                {
                    e.Graphics.DrawString(this.Text, this.Font, solidBrush, pt.X + 1, pt.Y + 1);
                }
            }
            //
            // else, paint the text and text shadow
            //
            else
            {
                //
                // paint text shadow
                //
                if (TextDropShadow)
                {
                    System.Drawing.Brush TransparentBrush0 = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(50, System.Drawing.Color.Black));
                    System.Drawing.Brush TransparentBrush1 = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(20, System.Drawing.Color.Black));

                    e.Graphics.DrawString(this.Text, this.Font, TransparentBrush0, pt.X, pt.Y + 1);
                    e.Graphics.DrawString(this.Text, this.Font, TransparentBrush0, pt.X + 1, pt.Y);

                    e.Graphics.DrawString(this.Text, this.Font, TransparentBrush1, pt.X + 1, pt.Y + 1);
                    e.Graphics.DrawString(this.Text, this.Font, TransparentBrush1, pt.X, pt.Y + 2);
                    e.Graphics.DrawString(this.Text, this.Font, TransparentBrush1, pt.X + 2, pt.Y);

                    TransparentBrush0.Dispose();
                    TransparentBrush1.Dispose();
                }
                //
                // paint text
                //
                using (var solidBrush = new SolidBrush(this.ForeColor))
                {
                    e.Graphics.DrawString(this.Text, this.Font, solidBrush, pt.X, pt.Y);
                }
            }
        }
Пример #47
0
        //used to fire an event to retrieve formatting info
        //and then draw the cell with this formatting info
        protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush foreBrush, bool alignToRight)
        {
            DataGridFormatCellEventArgs e = null;

            bool callBaseClass = true;

            //fire the formatting event
            if (SetCellFormat != null)
            {
                int col = this.DataGridTableStyle.GridColumnStyles.IndexOf(this);
                e = new DataGridFormatCellEventArgs(rowNum, col, this.GetColumnValueAtRow(source, rowNum));
                SetCellFormat(this, e);

                if (e.BackBrush != null)
                {
                    backBrush = e.BackBrush;
                }

                //if these properties set, then must call drawstring
                if (e.ForeBrush != null || e.TextFont != null)
                {
                    if (e.ForeBrush == null)
                    {
                        e.ForeBrush = foreBrush;
                    }
                    if (e.TextFont == null)
                    {
                        e.TextFont = this.DataGridTableStyle.DataGrid.Font;
                    }
                    g.FillRectangle(backBrush, bounds);
                    Region    saveRegion = g.Clip;
                    Rectangle rect       = new Rectangle(bounds.X, bounds.Y, bounds.Width, bounds.Height);
                    using (Region newRegion = new Region(rect))
                    {
                        g.Clip = newRegion;
                        int charWidth = (int)Math.Ceiling(g.MeasureString("c", e.TextFont, 20, StringFormat.GenericTypographic).Width);

                        string s        = this.GetColumnValueAtRow(source, rowNum).ToString();
                        int    maxChars = Math.Min(s.Length, (bounds.Width / charWidth));

                        try
                        {
                            g.DrawString(s.Substring(0, maxChars), e.TextFont, e.ForeBrush, bounds.X, bounds.Y + 2);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message.ToString());
                        }                         //empty catch
                        finally
                        {
                            g.Clip = saveRegion;
                        }
                    }
                    callBaseClass = false;
                }

                if (!e.UseBaseClassDrawing)
                {
                    callBaseClass = false;
                }
            }
            if (callBaseClass)
            {
                base.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight);
            }

            //clean up
            if (e != null)
            {
                if (e.BackBrushDispose)
                {
                    e.BackBrush.Dispose();
                }
                if (e.ForeBrushDispose)
                {
                    e.ForeBrush.Dispose();
                }
                if (e.TextFontDispose)
                {
                    e.TextFont.Dispose();
                }
            }
        }
Пример #48
0
        /// <summary>
        /// calculates the left/top edge for content.
        /// </summary>
        /// <param name="Alignment">the alignment of the content</param>
        /// <param name="rect">rectagular region to place content</param>
        /// <param name="nWidth">with of content</param>
        /// <param name="nHeight">height of content</param>
        /// <returns>returns the left/top edge to place content</returns>
        private System.Drawing.Point Calculate_LeftEdgeTopEdge(System.Drawing.ContentAlignment Alignment, System.Drawing.Rectangle rect, int nWidth, int nHeight)
        {
            System.Drawing.Point pt = new System.Drawing.Point(0, 0);
            switch (Alignment)
            {
            case System.Drawing.ContentAlignment.BottomCenter:
                pt.X = (rect.Width - nWidth) / 2;
                pt.Y = rect.Height - nHeight;
                break;

            case System.Drawing.ContentAlignment.BottomLeft:
                pt.X = 0;
                pt.Y = rect.Height - nHeight;
                break;

            case System.Drawing.ContentAlignment.BottomRight:
                pt.X = rect.Width - nWidth;
                pt.Y = rect.Height - nHeight;
                break;

            case System.Drawing.ContentAlignment.MiddleCenter:
                pt.X = (rect.Width - nWidth) / 2;
                pt.Y = (rect.Height - nHeight) / 2;
                break;

            case System.Drawing.ContentAlignment.MiddleLeft:
                pt.X = 0;
                pt.Y = (rect.Height - nHeight) / 2;
                break;

            case System.Drawing.ContentAlignment.MiddleRight:
                pt.X = rect.Width - nWidth;
                pt.Y = (rect.Height - nHeight) / 2;
                break;

            case System.Drawing.ContentAlignment.TopCenter:
                pt.X = (rect.Width - nWidth) / 2;
                pt.Y = 0;
                break;

            case System.Drawing.ContentAlignment.TopLeft:
                pt.X = 0;
                pt.Y = 0;
                break;

            case System.Drawing.ContentAlignment.TopRight:
                pt.X = rect.Width - nWidth;
                pt.Y = 0;
                break;
            }
            pt.X += rect.Left;
            pt.Y += rect.Top;
            return(pt);
        }
Пример #49
0
 public CompressedImage GetScreenshot6(System.Drawing.Rectangle cropRect)
 {
     return(GetImage("eb79be23-9623-4c08-86b4-c2cfd5fbf8b8", cropRect));
 }
Пример #50
0
        public void draw()
        {
            if (LEDSetup.OVERRIDE)
            {
                return;
            }
            if (device == null)
            {
                return;
            }
            byte[] serialData = LEDSetup.getMagicHeader();

            //Bitmap screenBitmap = getScreenGDI();
            Bitmap screenBitmap = getScreenDX();

            if (screenBitmap == null)
            {
                return;
            }

#if true
            for (int i = 0; i < LEDSetup.LED_C; i++)
            {
                int  r = 0, g = 0, b = 0, c = 0;
                long re = 0, gr = 0, bl = 0;
#if true
                var rect = new System.Drawing.Rectangle((int)LEDSetup.leds[i].Coords.X,
                                                        (int)LEDSetup.leds[i].Coords.Y, (int)LEDSetup.leds[i].Coords.Width,
                                                        (int)LEDSetup.leds[i].Coords.Height);
                byte[] dat;
                lock (screenBitmap)
                {
                    var bmpData = screenBitmap.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppRgb);
                    dat = new byte[bmpData.Stride * bmpData.Height];
                    System.Runtime.InteropServices.Marshal.Copy(bmpData.Scan0, dat, 0, dat.Length);
                    screenBitmap.UnlockBits(bmpData);
                }
                for (int d = 0; d < dat.Length; d += 4 * 60)
                {
                    // Format is actually Bgr despite the name above being Rgb
                    bl += dat[d] * dat[d];
                    gr += dat[d + 1] * dat[d + 1];
                    re += dat[d + 2] * dat[d + 2];
                    c++;
                }
#else
                for (int x = (int)LEDSetup.leds[i].Coords.Left; x < (int)LEDSetup.leds[i].Coords.Right; x += 10)
                {
                    for (int y = (int)LEDSetup.leds[i].Coords.Top; y < (int)LEDSetup.leds[i].Coords.Bottom; y += 10)
                    {
                        System.Drawing.Color col;
                        lock (screenBitmap)
                        {
                            col = screenBitmap.GetPixel(x, y);
                        }
                        re += (long)(col.R * col.R);
                        gr += (long)(col.G * col.G);
                        bl += (long)(col.B * col.B);
                        c++;
                    }
                }
#endif

                r = (int)(Math.Sqrt(re / c) * rc);
                g = (int)(Math.Sqrt(gr / c) * gc);
                b = (int)(Math.Sqrt(bl / c) * bc);
                if (r > 255)
                {
                    r = 255;
                }
                if (g > 255)
                {
                    g = 255;
                }
                if (b > 255)
                {
                    b = 255;
                }

                LEDSetup.processColor(i, serialData, r, g, b);
            }
#else
            Parallel.For(0, LEDSetup.LED_C, (i) =>
            {
                int r   = 0, g = 0, b = 0, c = 0;
                long re = 0, gr = 0, bl = 0;
                for (int x = (int)LEDSetup.leds[i].Coords.Left; x < (int)LEDSetup.leds[i].Coords.Right; x += 10)
                {
                    for (int y = (int)LEDSetup.leds[i].Coords.Top; y < (int)LEDSetup.leds[i].Coords.Bottom; y += 10)
                    {
                        System.Drawing.Color col;
                        lock (screenBitmap)
                        {
                            col = screenBitmap.GetPixel(x, y);
                        }
                        if (false)
                        {
                            re += (long)col.R;
                            gr += (long)col.G;
                            bl += (long)col.B;
                        }
                        else
                        {
                            re += (long)(col.R * col.R);
                            gr += (long)(col.G * col.G);
                            bl += (long)(col.B * col.B);
                        }
                        c++;
                    }
                }
                if (false)
                {
                    r = (int)(re / c);
                    g = (int)(gr / c);
                    b = (int)(bl / c);
                }
                else
                {
                    r = (int)Math.Sqrt(re / c);
                    g = (int)Math.Sqrt(gr / c);
                    b = (int)Math.Sqrt(bl / c);
                }
                if (r > 255)
                {
                    r = 255;
                }
                if (g > 255)
                {
                    g = 255;
                }
                if (b > 255)
                {
                    b = 255;
                }

                LEDSetup.processColor(i, serialData, r, g, b);
            });
#endif
            screenBitmap.Dispose();
            LEDSetup.sendSerialData(serialData);
        }
Пример #51
0
 public CompressedImage GetScreenshot3(System.Drawing.Rectangle cropRect)
 {
     return(GetImage("5a0edaa1-2ac7-40aa-a1c6-a1abc60a4028", cropRect));
 }
Пример #52
0
 public CompressedImage GetScreenshot1(System.Drawing.Rectangle cropRect)
 {
     return(GetImage("bfd88a1e-8471-4a5c-8118-9957174fcd78", cropRect));
 }
Пример #53
0
        public Bitmap getScreenDX()
        {
            if (System.Windows.Forms.Screen.AllScreens[0].Bounds.Width != LEDSetup.SCREEN_W)
            {
                return(null);
            }
            try
            {
                SharpDX.DXGI.Resource           screenResource;
                OutputDuplicateFrameInformation duplicateFrameInformation;

                // Try to get duplicated frame within given time
                duplicatedOutput.AcquireNextFrame(1000, out duplicateFrameInformation, out screenResource);

                // copy resource into memory that can be accessed by the CPU
                using (var screenTexture2D = screenResource.QueryInterface <Texture2D>())
                    device.ImmediateContext.CopyResource(screenTexture2D, screenTexture);

                // Get the desktop capture texture
                var mapSource = device.ImmediateContext.MapSubresource(screenTexture, 0, MapMode.Read, SharpDX.Direct3D11.MapFlags.None);

                // Create Drawing.Bitmap
                var bitmap     = new System.Drawing.Bitmap(LEDSetup.SCREEN_W, LEDSetup.SCREEN_H, PixelFormat.Format32bppArgb);
                var boundsRect = new System.Drawing.Rectangle(0, 0, LEDSetup.SCREEN_W, LEDSetup.SCREEN_H);

                // Copy pixels from screen capture Texture to GDI bitmap
                var mapDest   = bitmap.LockBits(boundsRect, ImageLockMode.WriteOnly, bitmap.PixelFormat);
                var sourcePtr = mapSource.DataPointer;
                var destPtr   = mapDest.Scan0;
                for (int y = 0; y < LEDSetup.SCREEN_H; y++)
                {
                    // Copy a single line
                    Utilities.CopyMemory(destPtr, sourcePtr, LEDSetup.SCREEN_W * 4);

                    // Advance pointers
                    sourcePtr = IntPtr.Add(sourcePtr, mapSource.RowPitch);
                    destPtr   = IntPtr.Add(destPtr, mapDest.Stride);
                }

                // Release source and dest locks
                bitmap.UnlockBits(mapDest);
                device.ImmediateContext.UnmapSubresource(screenTexture, 0);

                // Save the output
                //bitmap.Save(outputFileName, ImageFormat.Png);

                // Capture done

                screenResource.Dispose();
                duplicatedOutput.ReleaseFrame();

                invalid_calls = 0;
                return(bitmap);
            }
            catch (SharpDXException e)
            {
                if (e.ResultCode.Code != SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code)// && e.ResultCode != SharpDX.DXGI.ResultCode.InvalidCall.Result.Code)
                {
                    if (e.ResultCode.Code == SharpDX.DXGI.ResultCode.AccessLost.Result.Code)
                    {
                        Logger.QueueLine("Device access lost, reinitializing duplication");
                        setupDX();
                        System.Threading.Thread.Sleep(200);
                    }
                    else if (e.ResultCode.Code == SharpDX.DXGI.ResultCode.DeviceRemoved.Code)
                    {
                        Logger.QueueLine("Device removed, reinitializing duplication");
                        setupDX();
                        System.Threading.Thread.Sleep(200);
                    }
                    else if (e.ResultCode.Code == SharpDX.DXGI.ResultCode.InvalidCall.Code)
                    {
                        invalid_calls++;
                        if (invalid_calls >= 10)
                        {
                            Logger.QueueLine("Too many invalid calls, reinitializing duplication");
                            setupDX();
                        }
                        System.Threading.Thread.Sleep(200);
                    }
                    else
                    {
                        throw e;
                    }
                }
            }
            catch (Exception e)
            {
            }
            return(null);
        }
Пример #54
0
		public void Union (Rectangle rect)
		{                                    
                        Status status = GDIPlus.GdipCombineRegionRectI (nativeRegion, ref rect, CombineMode.Union);
                        GDIPlus.CheckStatus (status);
		}
Пример #55
0
 public CompressedImage GetScreenshot2(System.Drawing.Rectangle cropRect)
 {
     return(GetImage("f00973a6-966f-43ed-87ce-28508d2f8d41", cropRect));
 }
Пример #56
0
 protected override void Paint(sd.Graphics graphics, sd.Rectangle clipBounds, sd.Rectangle cellBounds, int rowIndex, swf.DataGridViewElementStates elementState, object value, object formattedValue, string errorText, swf.DataGridViewCellStyle cellStyle, swf.DataGridViewAdvancedBorderStyle advancedBorderStyle, swf.DataGridViewPaintParts paintParts)
 {
     Handler.Paint(graphics, clipBounds, ref cellBounds, rowIndex, elementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, ref paintParts);
     base.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
 }
Пример #57
0
    /// <summary>
    /// Loads a Direct2D Bitmap from a file using System.Drawing.Image.FromFile(...)
    /// </summary>
    /// <param name="renderTarget">The render target.</param>
    /// <param name="file">The file.</param>
    /// <returns>A D2D1 Bitmap</returns>
    public static Bitmap LoadFromFile(RenderTarget renderTarget, System.Drawing.Size newSize, string file)
    {
        // Loads from file using System.Drawing.Image
        System.Drawing.Bitmap bitmap;

        int width, height;

        if (newSize.IsEmpty)
        {
            bitmap = new System.Drawing.Bitmap(System.Drawing.Image.FromFile(file));
        }
        else if (newSize.Width == 0)
        {
            //scale to height
            bitmap = new System.Drawing.Bitmap(System.Drawing.Image.FromFile(file));
            height = newSize.Height;
            float ratio = bitmap.Width / (float)bitmap.Height;
            width  = (int)(height * ratio);
            bitmap = new System.Drawing.Bitmap(bitmap, width, height);
        }
        else if (newSize.Height == 0)
        {
            bitmap = new System.Drawing.Bitmap(System.Drawing.Image.FromFile(file));
            width  = newSize.Width;
            float ratio = bitmap.Height / (float)bitmap.Width;
            height = (int)(width * ratio);
            bitmap = new System.Drawing.Bitmap(bitmap, width, height);
        }
        else
        {
            bitmap = new System.Drawing.Bitmap(System.Drawing.Image.FromFile(file), newSize);
        }

        var sourceArea       = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);
        var bitmapProperties = new BitmapProperties(new PixelFormat(Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied));
        var size             = new Size2(bitmap.Width, bitmap.Height);

        // Transform pixels from BGRA to RGBA
        int stride = bitmap.Width * sizeof(int);

        using (var tempStream = new DataStream(bitmap.Height * stride, true, true))
        {
            // Lock System.Drawing.Bitmap
            var bitmapData = bitmap.LockBits(sourceArea, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

            // Convert all pixels
            for (int y = 0; y < bitmap.Height; y++)
            {
                int offset = bitmapData.Stride * y;
                for (int x = 0; x < bitmap.Width; x++)
                {
                    // Not optimized
                    byte B    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                    byte G    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                    byte R    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                    byte A    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                    int  rgba = R | (G << 8) | (B << 16) | (A << 24);
                    tempStream.Write(rgba);
                }
            }
            bitmap.UnlockBits(bitmapData);
            tempStream.Position = 0;

            return(new Bitmap(renderTarget, size, tempStream, stride, bitmapProperties));
        }
    }
Пример #58
0
		public void Complement (Rectangle rect)
		{
                        Status status = GDIPlus.GdipCombineRegionRectI (nativeRegion, ref rect, CombineMode.Complement);
                        GDIPlus.CheckStatus (status);
		}
Пример #59
0
      // ************************************************************************
      public void DrawObjectBoxes(ref Bitmap img, string objectType, int _xmin, int _ymin, int _xmax, int _ymax, string text)
      {
          using (Graphics gfxImage = Graphics.FromImage(img))
          {
              System.Drawing.Rectangle rect;
              System.Drawing.SizeF     size;
              Brush rectBrush;

              //get dimensions of the image and the picturebox
              float imgWidth  = img.Width;
              float imgHeight = img.Height;
              float boxWidth  = img.Width;  // pictureBox1.Width;
              float boxHeight = img.Height; //pictureBox1.Height;

              //these variables store the padding between image border and picturebox border
              int absX = 0;
              int absY = 0;

              //because the sizemode of the picturebox is set to 'zoom', the image is scaled down
              float scale = 1;

              //Comparing the aspect ratio of both the control and the image itself.
              if (imgWidth / imgHeight > boxWidth / boxHeight)      //if the image is p.e. 16:9 and the picturebox is 4:3
              {
                  scale = boxWidth / imgWidth;                      //get scale factor
                  absY  = (int)(boxHeight - scale * imgHeight) / 2; //padding on top and below the image
              }
              else                                                  //if the image is p.e. 4:3 and the picturebox is widescreen 16:9
              {
                  scale = boxHeight / imgHeight;                    //get scale factor
                  absX  = (int)(boxWidth - scale * imgWidth) / 2;   //padding left and right of the image
              }

              //2. inputted position values are for the original image size. As the image is probably smaller in the picturebox, the positions must be adapted.
              int xmin = (int)(scale * _xmin) + absX;
              int xmax = (int)(scale * _xmax) + absX;
              int ymin = (int)(scale * _ymin) + absY;
              int ymax = (int)(scale * _ymax) + absY;

              int penSize = 2;
              if (img.Height > 1200)
              {
                  penSize = 4;
              }
              else if (img.Height >= 800 && img.Height <= 1200)
              {
                  penSize = 3;
              }


              //3. paint rectangle
              Color boxColor = Color.FromArgb(150, this.GetBoxColor(objectType));
              rect = new System.Drawing.Rectangle(xmin, ymin, xmax - xmin, ymax - ymin);
              using (Pen pen = new Pen(boxColor, penSize)) { gfxImage.DrawRectangle(pen, rect); }   //draw rectangle

              // Text Color
              Brush textColor = (boxColor.GetBrightness() > 0.5 ? Brushes.Black : Brushes.White);

              float fontSize = 12 * ((float)img.Height / 1080);   // Scale for image sizes
              if (fontSize < 8)
              {
                  fontSize = 8;
              }
              Font textFont = new Font(FontFamily.GenericSansSerif, fontSize, FontStyle.Regular);

              //object name text below rectangle
              rect      = new System.Drawing.Rectangle(xmin - 1, ymax, (int)boxWidth, (int)boxHeight); //sets bounding box for drawn text
              rectBrush = new SolidBrush(boxColor);                                                    //sets background rectangle color

              gfxImage.SmoothingMode      = SmoothingMode.HighQuality;
              gfxImage.CompositingQuality = CompositingQuality.HighQuality;

              size = gfxImage.MeasureString(text, textFont);                              //finds size of text to draw the background rectangle
              gfxImage.FillRectangle(rectBrush, xmin - 1, ymax, size.Width, size.Height); //draw background rectangle for detection text
              gfxImage.DrawString(text, textFont, textColor, rect);                       //draw detection text
          }
      }
Пример #60
0
        public override void DrawAppointment(System.Drawing.Graphics g, System.Drawing.Rectangle rect, Appointment appointment, bool isSelected, int gripWidth)
        {
            StringFormat m_Format = new StringFormat();

            m_Format.Alignment     = StringAlignment.Near;
            m_Format.LineAlignment = StringAlignment.Near;

            Color start = InterpolateColors(appointment.Color, Color.White, 0.4f);
            Color end   = InterpolateColors(appointment.Color, Color.FromArgb(191, 210, 234), 0.7f);

            if ((appointment.Locked))
            {
                // Draw back
                using (Brush m_Brush = new System.Drawing.Drawing2D.HatchBrush(System.Drawing.Drawing2D.HatchStyle.LargeConfetti, Color.Blue, appointment.Color))
                    g.FillRectangle(m_Brush, rect);

                // little transparent
                start = Color.FromArgb(230, start);
                end   = Color.FromArgb(180, end);

                GraphicsPath path = new GraphicsPath();
                path.AddRectangle(rect);

                using (LinearGradientBrush aGB = new LinearGradientBrush(rect, start, end, LinearGradientMode.Vertical))
                    g.FillRectangle(aGB, rect);
            }
            else
            {
                // Draw back
                using (LinearGradientBrush aGB = new LinearGradientBrush(rect, start, end, LinearGradientMode.Vertical))
                    g.FillRectangle(aGB, rect);
            }

            if (isSelected)
            {
                Rectangle m_BorderRectangle = rect;

                using (Pen m_Pen = new Pen(appointment.BorderColor, 4))
                    g.DrawRectangle(m_Pen, rect);

                m_BorderRectangle.Inflate(2, 2);

                using (Pen m_Pen = new Pen(SystemColors.WindowFrame, 1))
                    g.DrawRectangle(m_Pen, m_BorderRectangle);

                m_BorderRectangle.Inflate(-4, -4);

                using (Pen m_Pen = new Pen(SystemColors.WindowFrame, 1))
                    g.DrawRectangle(m_Pen, m_BorderRectangle);
            }
            else
            {
                // Draw gripper
                Rectangle m_GripRectangle = rect;

                m_GripRectangle.Width = gripWidth + 1;

                start = InterpolateColors(appointment.BorderColor, appointment.Color, 0.2f);
                end   = InterpolateColors(appointment.BorderColor, Color.White, 0.6f);

                using (LinearGradientBrush aGB = new LinearGradientBrush(rect, start, end, LinearGradientMode.Vertical))
                    g.FillRectangle(aGB, m_GripRectangle);

                using (Pen m_Pen = new Pen(SystemColors.WindowFrame, 1))
                    g.DrawRectangle(m_Pen, rect);

                // Draw shadow lines
                int xLeft   = rect.X + 6;
                int xRight  = rect.Right + 1;
                int yTop    = rect.Y + 1;
                int yButton = rect.Bottom + 1;

                for (int i = 0; i < 5; i++)
                {
                    using (Pen shadow_Pen = new Pen(Color.FromArgb(70 - 12 * i, Color.Black)))
                    {
                        g.DrawLine(shadow_Pen, xLeft + i, yButton + i, xRight + i - 1, yButton + i); //horisontal lines
                        g.DrawLine(shadow_Pen, xRight + i, yTop + i, xRight + i, yButton + i);       //vertical
                    }
                }
            }

            rect.X += gripWidth;
            g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
            g.DrawString(appointment.Title, this.BaseFont, SystemBrushes.WindowText, rect, m_Format);
            g.TextRenderingHint = TextRenderingHint.SystemDefault;
        }