void controller_NewFrame(object sender, NewFrameEventArgs eventArgs) { if (!backproj) { Bitmap image = eventArgs.Frame; if (image == null) return; if (parent.faceForm != null && !parent.faceForm.IsDisposed) { MatchingTracker matching = parent.faceForm.faceController.Tracker as MatchingTracker; Rectangle rect = new Rectangle( matching.TrackingObject.Center.X, 0, image.Width - matching.TrackingObject.Center.X, matching.TrackingObject.Center.Y); rect.Intersect(new Rectangle(0, 0, image.Width, image.Height)); marker.Rectangles = new[] { matching.TrackingObject.Rectangle }; image = marker.Apply(image); } pictureBox.Image = image; } }
internal static Screen ScreenFromHandle(IntPtr windowHandle) { Microsoft.Xna.Framework.NativeMethods.RECT rect; int num = 0; Screen screen = null; Microsoft.Xna.Framework.NativeMethods.GetWindowRect(windowHandle, out rect); System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top); foreach (Screen screen2 in Screen.AllScreens) { System.Drawing.Rectangle rectangle2 = rectangle; rectangle2.Intersect(screen2.Bounds); int num2 = rectangle2.Width * rectangle2.Height; if (num2 > num) { num = num2; screen = screen2; } } if (screen == null) { screen = Screen.AllScreens[0]; } return(screen); }
protected override unsafe void ProcessFilter(UnmanagedImage sourceData, UnmanagedImage destinationData) { System.Drawing.Rectangle rect = this.rect; rect.Intersect(new System.Drawing.Rectangle(0, 0, sourceData.Width, sourceData.Height)); int left = rect.Left; int top = rect.Top; int num3 = rect.Bottom - 1; int width = rect.Width; int stride = sourceData.Stride; int num6 = destinationData.Stride; int num7 = Image.GetPixelFormatSize(sourceData.PixelFormat) / 8; int count = width * num7; byte *src = (byte *)((sourceData.ImageData.ToPointer() + (top * stride)) + (left * num7)); byte *dst = (byte *)destinationData.ImageData.ToPointer(); if (this.rect.Top < 0) { dst -= num6 * this.rect.Top; } if (this.rect.Left < 0) { dst -= num7 * this.rect.Left; } for (int i = top; i <= num3; i++) { SystemTools.CopyUnmanagedMemory(dst, src, count); src += stride; dst += num6; } }
protected virtual Rectangle AddApron(Rectangle rect, int apronRadius, Rectangle maxBounds) { rect.Inflate(apronRadius, apronRadius); rect.Intersect(maxBounds); return rect; }
public BucketWorker(Rectangle imgPlaneRect, Rectangle bucketRect, Display display, IPixelSampler pixelSampler, Scene scene, ManualResetEvent doneEvent) { _doneEvent = doneEvent; m_pixelSampler = pixelSampler; m_scene = scene; m_imgPlaneRect = imgPlaneRect; m_bucketRect = bucketRect; m_bucketRect.Intersect(imgPlaneRect); m_display = display; }
private void TransparentCommandBarControl_Invalidated(object sender, InvalidateEventArgs e) { Point absLoc = _parent.PointToScreen(e.InvalidRect.Location); Point relLoc = PointToClient(absLoc); Rectangle relRect = new Rectangle(relLoc, e.InvalidRect.Size); if (ClientRectangle.IntersectsWith(relRect)) { relRect.Intersect(ClientRectangle); Invalidate(relRect); } }
public override void OnDrawFinal(Graphics g, Bitmap bmp) { Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); rect.Intersect(Rectangle); using (Bitmap croppedImage = ImageHelpers.CropBitmap(bmp, rect)) { ImageHelpers.HighlightImage(croppedImage, HighlightColor); g.DrawImage(croppedImage, rect); } }
public void OnPaintTest2(IRenderEventArgs e) { Graphics g = ((GdiSurface)e.Surface).Graphics; SD.Drawing2D.Matrix save = g.Transform; g.Transform = Camera.Matrix.ToGdi(); Rectangle smaller = new Rectangle(start, new Size(50, 20)); Rectangle bigger = new Rectangle(start, new Size(55, 25)); Rectangle rect3 = new Rectangle(start, new Size(10, 10)); g.DrawRectangle(rectPen, smaller); g.DrawRectangle(rectPen, bigger); smaller.Inflate(-5, -5); bigger.Inflate(5, 5); //region.MakeEmpty (); region.MakeEmpty(); invPath.Reset(); invPath.FillMode = FillMode.Alternate; smaller.Intersect(bigger); //region.Intersect (smaller); //invPath.StartFigure (); invPath.AddRectangle(bigger); //invPath.CloseFigure(); //invPath.StartFigure(); invPath.AddRectangle(smaller); //invPath.CloseFigure(); // this is to simulage g.Clip, as it has the bounds-rectangle: region.Union(invPath.GetBounds()); region.Intersect(invPath); Region saveRegion = g.Clip; g.Clip = region; g.DrawPath(pathPen, invPath); //g.FillPath (regionBrush, invPath); g.FillRegion(regionBrush, g.Clip); if (!region.IsVisible(rect3)) { int x = 1; } //g.FillRegion (clipregionBrush, g.Clip); g.Transform = save; g.Clip = saveRegion; }
private void gauge_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { e.Graphics.Clear(Label.DefaultBackColor); Pen pen = new Pen(Color.Black); e.Graphics.DrawRectangle(pen, gauge.ClientRectangle); if (maxValue != 0) { int fillLevel = (int)((used/maxValue) * gauge.Size.Height); SolidBrush brush = new SolidBrush(barColor); Rectangle rect = new Rectangle(0, gauge.ClientSize.Height - fillLevel, gauge.ClientSize.Width, fillLevel); rect.Intersect(e.ClipRectangle); e.Graphics.FillRectangle(brush, rect); } }
public override void OnDrawFinal(Graphics g, Bitmap bmp) { if (PixelSize > 1) { Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); rect.Intersect(Rectangle); using (Bitmap croppedImage = ImageHelpers.CropBitmap(bmp, rect)) { ImageHelpers.Pixelate(croppedImage, PixelSize); g.DrawImage(croppedImage, rect); } } }
public override void OnDrawFinal(Graphics g, Bitmap bmp) { if (BlurRadius > 1) { Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); rect.Intersect(Rectangle); using (Bitmap croppedImage = ImageHelpers.CropBitmap(bmp, rect)) { ImageHelpers.BoxBlur(croppedImage, BlurRadius); g.DrawImage(croppedImage, rect); } } }
private bool SetBounds(Form form, ref Rectangle rectBounds) { // do this in such a way that we take into consideration the size of the screen // which may not be the same from machine to machine bool bChanged = false; Rectangle rectScreen = Screen.PrimaryScreen.WorkingArea; if (!rectScreen.Contains(rectBounds)) { rectBounds.Intersect(rectScreen); bChanged = true; } form.Bounds = rectBounds; return bChanged; }
protected override void OnMouseUp(MouseEventArgs args) { base.OnMouseUp(args); MsaglMouseEventArgs iArgs = CreateMouseEventArgs(args); gViewer.RaiseMouseUpEvent(iArgs); if (NeedToEraseRubber) { DrawXORFrame(); } if (!iArgs.Handled) { if (gViewer.OriginalGraph != null && MouseDraggingMode == DraggingMode.WindowZoom) { System.Drawing.Point p = mouseDownPoint; double f = Math.Max(Math.Abs(p.X - args.X), Math.Abs(p.Y - args.Y)) / GViewer.dpi; if (f > gViewer.ZoomWindowThreshold && zoomWindow) { mouseUpPoint = new System.Drawing.Point(args.X, args.Y); if (ClientRectangle.Contains(mouseUpPoint)) { System.Drawing.Rectangle r = GViewer.RectFromPoints(mouseDownPoint, mouseUpPoint); r.Intersect(gViewer.DestRect); if (GViewer.ModifierKeyWasPressed() == false) { mouseDownPoint.X = r.Left; mouseDownPoint.Y = r.Top; mouseUpPoint.X = r.Right; mouseUpPoint.Y = r.Bottom; P2 p1 = gViewer.ScreenToSource(mouseDownPoint); P2 p2 = gViewer.ScreenToSource(mouseUpPoint); double sc = Math.Min((double)ClientRectangle.Width / r.Width, (double)ClientRectangle.Height / (double)r.Height); P2 center = 0.5f * (p1 + p2); gViewer.Zoom(center.X, center.Y, sc * gViewer.ZoomF); } } } } } zoomWindow = false; }
public CVConnectedComp MeanShift(System.Drawing.Rectangle window, int termCriteria, int maxIterations, double eps) { System.Drawing.Rectangle realWindow = new System.Drawing.Rectangle(0, 0, Width, Height); if (!realWindow.IntersectsWith(window)) { CVConnectedComp cc = new CVConnectedComp(window); return(cc); } realWindow.Intersect(window); __CvRect wnd = new __CvRect(realWindow); __CvTermCriteria tc = PInvoke.cvTermCriteria(termCriteria, maxIterations, eps); __CvConnectedComp comp = new __CvConnectedComp(); PInvoke.cvMeanShift(Internal, wnd, tc, ref comp); CVUtils.CheckLastError(); return(new CVConnectedComp(ref comp)); }
protected override void OnPaint(PaintEventArgs pe) { //these settings aren't even needed for good perf, but they are helpful pe.Graphics.InterpolationMode = InterpolationMode.Low; pe.Graphics.CompositingQuality = CompositingQuality.HighSpeed; pe.Graphics.SmoothingMode = SmoothingMode.HighSpeed; if (this.image != null) { //draw empty area, if it exists, in an optimized way. if (this.AutoScrollPosition.X == 0) { int emptyRightAreaWidth = this.Width - this.image.Width; if (emptyRightAreaWidth > 0) { Rectangle fillRect = new Rectangle(this.image.Width, 0, emptyRightAreaWidth, this.Height); fillRect.Intersect(pe.ClipRectangle); pe.Graphics.FillRectangle(SystemBrushes.Control, fillRect); } } if (this.AutoScrollPosition.Y == 0) { int emptyRightAreaHeight = this.Height - this.image.Height; if (emptyRightAreaHeight > 0) { Rectangle fillRect = new Rectangle(0, this.image.Height, this.Width, emptyRightAreaHeight); fillRect.Intersect(pe.ClipRectangle); pe.Graphics.FillRectangle(SystemBrushes.Control, fillRect); } } //calculate the visible area of the bitmap Rectangle bitmapRect = new Rectangle(this.AutoScrollPosition.X, this.AutoScrollPosition.Y, this.image.Width, this.image.Height); Rectangle visibleClientRect = bitmapRect; visibleClientRect.Intersect(pe.ClipRectangle); if (visibleClientRect.Width == 0 || visibleClientRect.Height == 0) { return; } Rectangle visibleBitmapRect = visibleClientRect; visibleBitmapRect.Offset(-this.AutoScrollPosition.X, -this.AutoScrollPosition.Y); pe.Graphics.DrawImage(this.image, visibleClientRect, visibleBitmapRect, GraphicsUnit.Pixel); } else //if no bitmap just fill with background color { pe.Graphics.FillRectangle(SystemBrushes.Control, pe.ClipRectangle); } }
public static void RenderOneToOne(Surface dst, Surface source, Point offset) { unsafe { Rectangle srcRect = new Rectangle(offset, dst.Size); srcRect.Intersect(source.Bounds); for (int dstRow = 0; dstRow < srcRect.Height; ++dstRow) { ColorBgra* dstRowPtr = dst.GetRowAddressUnchecked(dstRow); ColorBgra* srcRowPtr = source.GetPointAddressUnchecked(offset.X, dstRow + offset.Y); int dstCol = offset.X; int dstColEnd = offset.X + srcRect.Width; int checkerY = dstRow + offset.Y; while (dstCol < dstColEnd) { int b = srcRowPtr->B; int g = srcRowPtr->G; int r = srcRowPtr->R; int a = srcRowPtr->A; // Blend it over the checkerboard background int v = (((dstCol ^ checkerY) & 8) << 3) + 191; a = a + (a >> 7); int vmia = v * (256 - a); r = ((r * a) + vmia) >> 8; g = ((g * a) + vmia) >> 8; b = ((b * a) + vmia) >> 8; dstRowPtr->Bgra = (uint)b + ((uint)g << 8) + ((uint)r << 16) + ((uint)255 << 24); ++dstRowPtr; ++srcRowPtr; ++dstCol; } } } }
public static Edges DetectEdgesCollision(Rectangle a, Rectangle b) { var result = Edges.None; if (a == b) return Edges.Identical; b.Intersect(a); if (b.IsEmpty) return Edges.None; if (a == b) return Edges.Covers; if (a.Top == b.Top && (a.Right >= b.Right && a.Left <= b.Left)) result |= Edges.Top; if (a.Bottom == b.Bottom && (a.Right >= b.Right && a.Left <= b.Left)) result |= Edges.Bottom; if (a.Left == b.Left && (a.Bottom >= b.Bottom && a.Top <= b.Top)) result |= Edges.Left; if (a.Right == b.Right && (a.Bottom >= b.Bottom && a.Top <= b.Top)) result |= Edges.Right; return result == Edges.None ? Edges.Inside : result; }
public virtual void PixBlt(IPixelArray pixArray, int x, int y) { // 1. Calculate the intersection intended destination rectangle // of the pixArray and the boundary of the pixelArray we're // holding onto. Rectangle srcRect = new Rectangle(x, y, pixArray.Width, pixArray.Height); // Create the boundary rectangle for our destination Rectangle dstRect = new Rectangle(0, 0, fDstAccess.Width, fDstAccess.Height); // Create the intersection of the dstRect and the srcRect srcRect.Intersect(dstRect); // If there is no intersection, then just return if (srcRect.IsEmpty) return; Rectangle srcBoundary = srcRect; srcBoundary.Offset(-x, -y); PixmapShardBlt(pixArray, srcBoundary, srcRect); }
public void AddPixelRangeToRefreshQueue(Rectangle pixelRange, bool cascadeToOtherMatrixes) { // limit refresh range to screen resolution pixelRange.Intersect(VisibleSurfaces.MaxSurfaceSize); // cascade to other refresh queues if required if (cascadeToOtherMatrixes) { if (RefreshQueueAreaAdded != null) RefreshQueueAreaAdded(new RefreshQueueAreaAddedEventArgs(_layer, pixelRange)); } // check all existing pixel ranges for an overlap with the new range for (int i = 0; i < _rects.Count; i++) { // if this pixel range is already included, just return if (_rects[i].Contains(pixelRange)) return; } // if we make it this far, this includes a new area to refresh isDirty = true; _rects.Add(pixelRange); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Paints the current <see cref="T:System.Windows.Forms.DataGridViewCell"></see>. /// </summary> /// <param name="graphics">The <see cref="T:System.Drawing.Graphics"></see> used to /// paint the <see cref="T:System.Windows.Forms.DataGridViewCell"></see>.</param> /// <param name="clipBounds">A <see cref="T:System.Drawing.Rectangle"></see> that /// represents the area of the <see cref="T:System.Windows.Forms.DataGridView"></see> /// that needs to be repainted.</param> /// <param name="cellBounds">A <see cref="T:System.Drawing.Rectangle"></see> that /// contains the bounds of the <see cref="T:System.Windows.Forms.DataGridViewCell"></see> /// that is being painted.</param> /// <param name="rowIndex">The row index of the cell that is being painted.</param> /// <param name="cellState">A bitwise combination of /// <see cref="T:System.Windows.Forms.DataGridViewElementStates"></see> values that /// specifies the state of the cell.</param> /// <param name="value">The data of the <see cref="T:System.Windows.Forms.DataGridViewCell"> /// </see> that is being painted.</param> /// <param name="formattedValue">The formatted data of the /// <see cref="T:System.Windows.Forms.DataGridViewCell"></see> that is being painted. /// </param> /// <param name="errorText">An error message that is associated with the cell.</param> /// <param name="cellStyle">A <see cref="T:System.Windows.Forms.DataGridViewCellStyle"> /// </see> that contains formatting and style information about the cell.</param> /// <param name="advancedBorderStyle">A /// <see cref="T:System.Windows.Forms.DataGridViewAdvancedBorderStyle"></see> that /// contains border styles for the cell that is being painted.</param> /// <param name="paintParts">A bitwise combination of the /// <see cref="T:System.Windows.Forms.DataGridViewPaintParts"></see> values that /// specifies which parts of the cell need to be painted.</param> /// ------------------------------------------------------------------------------------ protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { if (!m_fAllowPaint) return; // Clear the background Region background = new Region(cellBounds); background.Xor(GetCellContentDisplayRectangle(advancedBorderStyle)); background.Intersect(clipBounds); graphics.FillRegion(SystemBrushes.Window, background); // Invalidate the view so that it redraws if (m_Control != null) { Point pt = m_Control.PointToClient(DataGridView.PointToScreen(new Point(clipBounds.X, clipBounds.Y))); Rectangle borderRect = BorderWidths(advancedBorderStyle); Rectangle toDraw = new Rectangle(0, 0, cellBounds.Width, cellBounds.Height); Rectangle clientClip = new Rectangle(pt.X, pt.Y, clipBounds.Width, clipBounds.Height); toDraw.Intersect(clientClip); m_Control.Invalidate(toDraw, true); m_Control.Update(); } // Finally draw the borders if ((paintParts & DataGridViewPaintParts.Border) == DataGridViewPaintParts.Border) PaintBorder(graphics, clipBounds, cellBounds, cellStyle, advancedBorderStyle); }
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { int currentXPos = 0; int currentYPos = 0; bool adjustScrollBars = false; Graphics g = e.Graphics; Rectangle clipRectangle = e.ClipRectangle; if (updateMargin != null) { try { updateMargin.Paint(g, updateMargin.DrawingPosition); } catch (Exception ex) { Console.WriteLine("Got exception : " + ex); } // clipRectangle.Intersect(updateMargin.DrawingPosition); } if (clipRectangle.Width <= 0 || clipRectangle.Height <= 0) { return; } if (this.TextEditorProperties.UseAntiAliasedFont) { g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; } else { g.TextRenderingHint = TextRenderingHint.SystemDefault; } foreach (AbstractMargin margin in leftMargins) { if (margin.IsVisible) { Rectangle marginRectangle = new Rectangle(currentXPos , currentYPos, margin.Size.Width, Height - currentYPos); if (marginRectangle != margin.DrawingPosition) { adjustScrollBars = true; margin.DrawingPosition = marginRectangle; } currentXPos += margin.DrawingPosition.Width; if (clipRectangle.IntersectsWith(marginRectangle)) { marginRectangle.Intersect(clipRectangle); if (!marginRectangle.IsEmpty) { try { margin.Paint(g, marginRectangle); } catch (Exception ex) { Console.WriteLine("Got exception : " + ex); } } } } } Rectangle textViewArea = new Rectangle(currentXPos, currentYPos, Width - currentXPos, Height - currentYPos); if (textViewArea != textView.DrawingPosition) { adjustScrollBars = true; textView.DrawingPosition = textViewArea; } if (clipRectangle.IntersectsWith(textViewArea)) { textViewArea.Intersect(clipRectangle); if (!textViewArea.IsEmpty) { try { textView.Paint(g, textViewArea); } catch (Exception ex) { Console.WriteLine("Got exception : " + ex); } } } if (adjustScrollBars) { try { this.motherTextAreaControl.AdjustScrollBars(null, null); } catch (Exception) {} } try { Caret.UpdateCaretPosition(); } catch (Exception) {} base.OnPaint(e); }
private Rectangle GetClippedBounds(Rectangle r) { Rectangle v = GridColumn.SViewRect; if (GridColumn.GridPanel.IsVFrozen == false) { int n = GridColumn.GridPanel.FixedRowHeight - (GridColumn.GridPanel.FixedHeaderHeight); v.Y -= n; v.Height += n; } else { if (r.Y < v.Y) { v.Height += (v.Y - r.Y); v.Y = r.Y; } } if (GridColumn.IsHFrozen == false) { GridColumn pcol = GridColumn.GridPanel.Columns.GetLastVisibleFrozenColumn(); if (pcol != null) { int n = pcol.BoundsRelative.Right - v.X; v.X += n; v.Width -= n; } } //r.Width -= 1; //r.Height -= 1; r.Intersect(v); return (r); }
public DnnPage() : base() { var button = this.GetButton(); button.Text = "Perform Mask-rcnn Detection"; button.Clicked += OnButtonClicked; OnImagesLoaded += async(sender, image) => { if (image == null || image[0] == null) { return; } SetMessage("Please wait..."); SetImage(null); Task <Tuple <Mat, String, long> > t = new Task <Tuple <Mat, String, long> >( () => { InitDetector(); String msg = String.Empty; using (Mat blob = DnnInvoke.BlobFromImage(image[0])) using (VectorOfMat tensors = new VectorOfMat()) { _maskRcnnDetector.SetInput(blob, "image_tensor"); Stopwatch watch = Stopwatch.StartNew(); _maskRcnnDetector.Forward(tensors, new string[] { "detection_out_final", "detection_masks" }); watch.Stop(); msg = String.Format("Mask RCNN inception completed in {0} milliseconds.", watch.ElapsedMilliseconds); using (Mat boxes = tensors[0]) using (Mat masks = tensors[1]) { System.Drawing.Size imgSize = image[0].Size; float[,,,] boxesData = boxes.GetData(true) as float[, , , ]; int numDetections = boxesData.GetLength(2); for (int i = 0; i < numDetections; i++) { float score = boxesData[0, 0, i, 2]; if (score > 0.5) { int classId = (int)boxesData[0, 0, i, 1]; String label = _labels[classId]; MCvScalar color = _colors[classId]; float left = boxesData[0, 0, i, 3] * imgSize.Width; float top = boxesData[0, 0, i, 4] * imgSize.Height; float right = boxesData[0, 0, i, 5] * imgSize.Width; float bottom = boxesData[0, 0, i, 6] * imgSize.Height; RectangleF rectF = new RectangleF(left, top, right - left, bottom - top); Rectangle rect = Rectangle.Round(rectF); rect.Intersect(new Rectangle(Point.Empty, imgSize)); CvInvoke.Rectangle(image[0], rect, new MCvScalar(0, 0, 0, 0), 1); CvInvoke.PutText(image[0], label, rect.Location, FontFace.HersheyComplex, 1.0, new MCvScalar(0, 0, 255), 2); int[] masksDim = masks.SizeOfDimension; using (Mat mask = new Mat( masksDim[2], masksDim[3], DepthType.Cv32F, 1, masks.GetDataPointer(i, classId), masksDim[3] * masks.ElementSize)) using (Mat maskLarge = new Mat()) using (Mat maskLargeInv = new Mat()) using (Mat subRegion = new Mat(image[0], rect)) using (Mat largeColor = new Mat(subRegion.Size, Emgu.CV.CvEnum.DepthType.Cv8U, 3)) { CvInvoke.Resize(mask, maskLarge, rect.Size); //give the mask at least 30% transparency using (ScalarArray sa = new ScalarArray(0.7)) CvInvoke.Min(sa, maskLarge, maskLarge); //Create the inverse mask for the original image using (ScalarArray sa = new ScalarArray(1.0)) CvInvoke.Subtract(sa, maskLarge, maskLargeInv); //The mask color largeColor.SetTo(color); if (subRegion.NumberOfChannels == 4) { using (Mat bgrSubRegion = new Mat()) { CvInvoke.CvtColor(subRegion, bgrSubRegion, ColorConversion.Bgra2Bgr); CvInvoke.BlendLinear(largeColor, bgrSubRegion, maskLarge, maskLargeInv, bgrSubRegion); CvInvoke.CvtColor(bgrSubRegion, subRegion, ColorConversion.Bgr2Bgra); } } else { CvInvoke.BlendLinear(largeColor, subRegion, maskLarge, maskLargeInv, subRegion); } } } } } } long time = 0; return(new Tuple <Mat, String, long>(image[0], msg, time)); }); t.Start(); var result = await t; SetImage(t.Result.Item1); //String computeDevice = CvInvoke.UseOpenCL ? "OpenCL: " + Ocl.Device.Default.Name : "CPU"; SetMessage(t.Result.Item2); }; }
private void PaintCurrentBytesSign(Graphics g) { if (_keyInterpreter != null && Focused && _bytePos != -1 && Enabled) { if (_keyInterpreter.GetType() == typeof (KeyInterpreter)) { if (_selectionLength == 0) { Point gp = GetGridBytePoint(_bytePos - _startByte); PointF pf = GetByteStringPointF(gp); var s = new Size((int) _charSize.Width, (int) _charSize.Height); var r = new Rectangle((int) pf.X, (int) pf.Y, s.Width, s.Height); if (r.IntersectsWith(_recStringView)) { r.Intersect(_recStringView); PaintCurrentByteSign(g, r); } } else { var lineWidth = (int) (_recStringView.Width - _charSize.Width); Point startSelGridPoint = GetGridBytePoint(_bytePos - _startByte); PointF startSelPointF = GetByteStringPointF(startSelGridPoint); Point endSelGridPoint = GetGridBytePoint(_bytePos - _startByte + _selectionLength - 1); PointF endSelPointF = GetByteStringPointF(endSelGridPoint); int multiLine = endSelGridPoint.Y - startSelGridPoint.Y; if (multiLine == 0) { var singleLine = new Rectangle( (int) startSelPointF.X, (int) startSelPointF.Y, (int) (endSelPointF.X - startSelPointF.X + _charSize.Width), (int) _charSize.Height); if (singleLine.IntersectsWith(_recStringView)) { singleLine.Intersect(_recStringView); PaintCurrentByteSign(g, singleLine); } } else { var firstLine = new Rectangle( (int) startSelPointF.X, (int) startSelPointF.Y, (int) (_recStringView.X + lineWidth - startSelPointF.X + _charSize.Width), (int) _charSize.Height); if (firstLine.IntersectsWith(_recStringView)) { firstLine.Intersect(_recStringView); PaintCurrentByteSign(g, firstLine); } if (multiLine > 1) { var betweenLines = new Rectangle( _recStringView.X, (int) (startSelPointF.Y + _charSize.Height), (_recStringView.Width), (int) (_charSize.Height*(multiLine - 1))); if (betweenLines.IntersectsWith(_recStringView)) { betweenLines.Intersect(_recStringView); PaintCurrentByteSign(g, betweenLines); } } var lastLine = new Rectangle( _recStringView.X, (int) endSelPointF.Y, (int) (endSelPointF.X - _recStringView.X + _charSize.Width), (int) _charSize.Height); if (lastLine.IntersectsWith(_recStringView)) { lastLine.Intersect(_recStringView); PaintCurrentByteSign(g, lastLine); } } } } else { if (_selectionLength == 0) { Point gp = GetGridBytePoint(_bytePos - _startByte); PointF pf = GetBytePointF(gp); var s = new Size((int) _charSize.Width*2, (int) _charSize.Height); var r = new Rectangle((int) pf.X, (int) pf.Y, s.Width, s.Height); PaintCurrentByteSign(g, r); } else { var lineWidth = (int) (_recHex.Width - _charSize.Width*5); Point startSelGridPoint = GetGridBytePoint(_bytePos - _startByte); PointF startSelPointF = GetBytePointF(startSelGridPoint); Point endSelGridPoint = GetGridBytePoint(_bytePos - _startByte + _selectionLength - 1); PointF endSelPointF = GetBytePointF(endSelGridPoint); int multiLine = endSelGridPoint.Y - startSelGridPoint.Y; if (multiLine == 0) { var singleLine = new Rectangle( (int) startSelPointF.X, (int) startSelPointF.Y, (int) (endSelPointF.X - startSelPointF.X + _charSize.Width*2), (int) _charSize.Height); if (singleLine.IntersectsWith(_recHex)) { singleLine.Intersect(_recHex); PaintCurrentByteSign(g, singleLine); } } else { var firstLine = new Rectangle( (int) startSelPointF.X, (int) startSelPointF.Y, (int) (_recHex.X + lineWidth - startSelPointF.X + _charSize.Width*2), (int) _charSize.Height); if (firstLine.IntersectsWith(_recHex)) { firstLine.Intersect(_recHex); PaintCurrentByteSign(g, firstLine); } if (multiLine > 1) { var betweenLines = new Rectangle( _recHex.X, (int) (startSelPointF.Y + _charSize.Height), (int) (lineWidth + _charSize.Width*2), (int) (_charSize.Height*(multiLine - 1))); if (betweenLines.IntersectsWith(_recHex)) { betweenLines.Intersect(_recHex); PaintCurrentByteSign(g, betweenLines); } } var lastLine = new Rectangle( _recHex.X, (int) endSelPointF.Y, (int) (endSelPointF.X - _recHex.X + _charSize.Width*2), (int) _charSize.Height); if (lastLine.IntersectsWith(_recHex)) { lastLine.Intersect(_recHex); PaintCurrentByteSign(g, lastLine); } } } } } }
/// <summary> /// Rendering-method /// </summary> public void Render() { if (deviceLost) { AttemptRecovery(); } if (deviceLost) { return; } if (_device == null) { return; } try { Rectangle screen = _parent.GetScreen(); double zoom = _parent.GetZoom(); //Clear the backbuffer _device.Clear(ClearFlags.Target, new SharpDX.Color(_deviceBackColor.R, _deviceBackColor.B, _deviceBackColor.G, _deviceBackColor.A), 1.0f, 0); //Begin the scene _device.BeginScene(); sprite.Transform = Matrix.Scaling((float)zoom, (float)zoom, 1f); sprite2.Begin(SpriteFlags.AlphaBlend); if (zoom > 1) { // If zoomin, just do near-neighbor scaling _device.SetSamplerState(0, SamplerState.MinFilter, TextureFilter.Point); _device.SetSamplerState(0, SamplerState.MagFilter, TextureFilter.Point); _device.SetSamplerState(0, SamplerState.MipFilter, TextureFilter.Point); } sprite.Begin(SpriteFlags.AlphaBlend | SpriteFlags.DoNotModifyRenderState); // Render of scene here if (OnRender != null) { OnRender(this, new DeviceEventArgs(_device)); } sprite.Transform = Matrix.Scaling(1f, 1f, 1f); Rectangle rect1 = new Rectangle(DrawWidth - screen.X, 0, Width - DrawWidth, Height); rect1.Intersect(new Rectangle(0, 0, screen.Width, screen.Height)); Rectangle rect2 = new Rectangle(0, DrawHeight - screen.Y, DrawWidth, Height - DrawHeight); rect2.Intersect(new Rectangle(0, 0, screen.Width, screen.Height)); DrawTexture(tx, new Rectangle(0, 0, rect1.Width, rect1.Height), new Vector3(0, 0, 0), new Vector3(rect1.X, rect1.Y, 0), SystemColors.Control); DrawTexture(tx, new Rectangle(0, 0, rect2.Width, rect2.Height), new Vector3(0, 0, 0), new Vector3(rect2.X, rect2.Y, 0), SystemColors.Control); sprite.End(); sprite2.End(); //End the scene _device.EndScene(); _device.Present(); } catch (SharpDXException ex) { if (ex.ResultCode == ResultCode.DeviceLost) { Editor.Instance.DeviceExceptionDialog(); } else { Editor.Instance.DeviceExceptionDialog(); } } }
public DnnPage() : base() { var button = this.GetButton(); button.Text = "Perform Mask-rcnn Detection"; button.Clicked += OnButtonClicked; OnImagesLoaded += async(sender, image) => { if (image == null || image[0] == null) { return; } SetMessage("Please wait..."); SetImage(null); Task <Tuple <Mat, String, long> > t = new Task <Tuple <Mat, String, long> >( () => { String configFile = "mask_rcnn_inception_v2_coco_2018_01_28.pbtxt"; #if __ANDROID__ String path = System.IO.Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads, "dnn_data"); FileInfo configFileInfo = AndroidFileAsset.WritePermanantFileAsset(Android.App.Application.Context, configFile, "dnn_data", AndroidFileAsset.OverwriteMethod.AlwaysOverwrite); configFile = configFileInfo.FullName; #else String path = "./dnn_data/"; #endif String graphFile = DnnDownloadFile(path, "frozen_inference_graph.pb"); String lookupFile = DnnDownloadFile(path, "coco-labels-paper.txt"); string[] labels = File.ReadAllLines(lookupFile); Emgu.CV.Dnn.Net net = Emgu.CV.Dnn.DnnInvoke.ReadNetFromTensorflow(graphFile, configFile); Mat blob = DnnInvoke.BlobFromImage(image[0]); net.SetInput(blob, "image_tensor"); using (VectorOfMat tensors = new VectorOfMat()) { net.Forward(tensors, new string[] { "detection_out_final", "detection_masks" }); using (Mat boxes = tensors[0]) using (Mat masks = tensors[1]) { System.Drawing.Size imgSize = image[0].Size; float[,,,] boxesData = boxes.GetData(true) as float[, , , ]; //float[,,,] masksData = masks.GetData(true) as float[,,,]; int numDetections = boxesData.GetLength(2); for (int i = 0; i < numDetections; i++) { float score = boxesData[0, 0, i, 2]; if (score > 0.5) { int classId = (int)boxesData[0, 0, i, 1]; String label = labels[classId]; float left = boxesData[0, 0, i, 3] * imgSize.Width; float top = boxesData[0, 0, i, 4] * imgSize.Height; float right = boxesData[0, 0, i, 5] * imgSize.Width; float bottom = boxesData[0, 0, i, 6] * imgSize.Height; RectangleF rectF = new RectangleF(left, top, right - left, bottom - top); Rectangle rect = Rectangle.Round(rectF); rect.Intersect(new Rectangle(Point.Empty, imgSize)); CvInvoke.Rectangle(image[0], rect, new MCvScalar(0, 0, 0, 0), 1); CvInvoke.PutText(image[0], label, rect.Location, FontFace.HersheyComplex, 1.0, new MCvScalar(0, 0, 255), 2); int[] masksDim = masks.SizeOfDimension; using (Mat mask = new Mat( masksDim[2], masksDim[3], DepthType.Cv32F, 1, //masks.DataPointer + //(i * masksDim[1] + classId ) //* masksDim[2] * masksDim[3] * masks.ElementSize, masks.GetDataPointer(i, classId), masksDim[3] * masks.ElementSize)) using (Mat maskLarge = new Mat()) using (Mat maskLargeInv = new Mat()) using (Mat subRegion = new Mat(image[0], rect)) using (Mat largeColor = new Mat(subRegion.Size, Emgu.CV.CvEnum.DepthType.Cv8U, 3)) { CvInvoke.Resize(mask, maskLarge, rect.Size); //give the mask at least 30% transparency using (ScalarArray sa = new ScalarArray(0.7)) CvInvoke.Min(sa, maskLarge, maskLarge); //Create the inverse mask for the original image using (ScalarArray sa = new ScalarArray(1.0)) CvInvoke.Subtract(sa, maskLarge, maskLargeInv); //The mask color largeColor.SetTo(new Emgu.CV.Structure.MCvScalar(255, 0, 0)); if (subRegion.NumberOfChannels == 4) { using (Mat bgrSubRegion = new Mat()) { CvInvoke.CvtColor(subRegion, bgrSubRegion, ColorConversion.Bgra2Bgr); CvInvoke.BlendLinear(largeColor, bgrSubRegion, maskLarge, maskLargeInv, bgrSubRegion); CvInvoke.CvtColor(bgrSubRegion, subRegion, ColorConversion.Bgr2Bgra); } } else { CvInvoke.BlendLinear(largeColor, subRegion, maskLarge, maskLargeInv, subRegion); } } } } } } long time = 0; return(new Tuple <Mat, String, long>(image[0], null, time)); }); t.Start(); var result = await t; SetImage(t.Result.Item1); String computeDevice = CvInvoke.UseOpenCL ? "OpenCL: " + Ocl.Device.Default.Name : "CPU"; SetMessage(t.Result.Item2); }; }
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { int currentXPos = 0; int currentYPos = 0; bool adjustScrollBars = false; Graphics g = e.Graphics; Rectangle clipRectangle = e.ClipRectangle; bool isFullRepaint = clipRectangle.X == 0 && clipRectangle.Y == 0 && clipRectangle.Width == this.Width && clipRectangle.Height == this.Height; g.TextRenderingHint = this.TextEditorProperties.TextRenderingHint; if (updateMargin != null) { updateMargin.Paint(g, updateMargin.DrawingPosition); // clipRectangle.Intersect(updateMargin.DrawingPosition); } if (clipRectangle.Width <= 0 || clipRectangle.Height <= 0) { return; } foreach (AbstractMargin margin in leftMargins) { if (margin.IsVisible) { Rectangle marginRectangle = new Rectangle(currentXPos , currentYPos, margin.Size.Width, Height - currentYPos); if (marginRectangle != margin.DrawingPosition) { // margin changed size if (!isFullRepaint && !clipRectangle.Contains(marginRectangle)) { Invalidate(); // do a full repaint } adjustScrollBars = true; margin.DrawingPosition = marginRectangle; } currentXPos += margin.DrawingPosition.Width; if (clipRectangle.IntersectsWith(marginRectangle)) { marginRectangle.Intersect(clipRectangle); if (!marginRectangle.IsEmpty) { margin.Paint(g, marginRectangle); } } } } Rectangle textViewArea = new Rectangle(currentXPos, currentYPos, Width - currentXPos, Height - currentYPos); if (textViewArea != textView.DrawingPosition) { adjustScrollBars = true; textView.DrawingPosition = textViewArea; // update caret position (but outside of WM_PAINT!) BeginInvoke((MethodInvoker)caret.UpdateCaretPosition); } if (clipRectangle.IntersectsWith(textViewArea)) { textViewArea.Intersect(clipRectangle); if (!textViewArea.IsEmpty) { textView.Paint(g, textViewArea); } } if (adjustScrollBars) { this.motherTextAreaControl.AdjustScrollBars(); } // we cannot update the caret position here, it's not allowed to call the caret API inside WM_PAINT //Caret.UpdateCaretPosition(); base.OnPaint(e); }
public virtual void DrawContent(Graphics graphics, Bitmap bmp, RenderMode renderMode, Rectangle clipRectangle) { if (Children.Count > 0) { if (Status != EditStatus.IDLE) { DrawSelectionBorder(graphics, Bounds); } else { if (clipRectangle.Width != 0 && clipRectangle.Height != 0) { foreach(IFilter filter in Filters) { if (filter.Invert) { filter.Apply(graphics, bmp, Bounds, renderMode); } else { Rectangle drawingRect = new Rectangle(Bounds.Location, Bounds.Size); drawingRect.Intersect(clipRectangle); if(filter is MagnifierFilter) { // quick&dirty bugfix, because MagnifierFilter behaves differently when drawn only partially // what we should actually do to resolve this is add a better magnifier which is not that special filter.Apply(graphics, bmp, Bounds, renderMode); } else { filter.Apply(graphics, bmp, drawingRect, renderMode); } } } } } } Draw(graphics, renderMode); }
/// <summary> /// Apply filter to an unmanaged image or its part. /// </summary> /// /// <param name="image">Unmanaged image to apply filter to.</param> /// <param name="rect">Image rectangle for processing by the filter.</param> /// /// <remarks>The method applies the filter directly to the provided source image.</remarks> /// /// <exception cref="UnsupportedImageFormatException">Unsupported pixel format of the source image.</exception> /// public void ApplyInPlace(UnmanagedImage image, Rectangle rect) { // check pixel format of the source image CheckSourceFormat(image.PixelFormat); // validate rectangle rect.Intersect(new Rectangle(0, 0, image.Width, image.Height)); // process the filter if rectangle is not empty if ((rect.Width | rect.Height) != 0) { // create a copy of the source image int size = image.Stride * image.Height; IntPtr imageCopy = MemoryManager.Alloc(size); AForge.SystemTools.CopyUnmanagedMemory(imageCopy, image.ImageData, size); // process the filter ProcessFilter( new UnmanagedImage(imageCopy, image.Width, image.Height, image.Stride, image.PixelFormat), image, rect); MemoryManager.Free(imageCopy); } }
/// <summary> /// Constructor which stores the image and locks it when called /// </summary> /// <param name="bitmap"></param> protected FastBitmap(Bitmap bitmap, Rectangle area) { this.bitmap = bitmap; Rectangle bitmapArea = new Rectangle(Point.Empty, bitmap.Size); if (area != Rectangle.Empty) { area.Intersect(bitmapArea); this.area = area; } else { this.area = bitmapArea; } // As the lock takes care that only the specified area is made available we need to calculate the offset Left = area.Left; Top = area.Top; // Default cliping is done to the area without invert Clip = this.area; InvertClip = false; // Always lock, so we don't need to do this ourselves Lock(); }
/// <summary> /// Clears a portion of a surface to transparent. /// </summary> /// <param name="surface">The surface to partially clear</param> /// <param name="roi">The rectangle to clear</param> private unsafe void ClearBackground(Surface surface, Rectangle roi) { roi.Intersect(surface.Bounds); for (int y = roi.Top; y < roi.Bottom; y++) { ColorBgra *ptr = surface.GetPointAddressUnchecked(roi.Left, y); Memory.SetToZero(ptr, (ulong)roi.Width * ColorBgra.SizeOf); } }
/// ------------------------------------------------------------------------------------ /// <summary> /// Draw as much of this page as will fit in the clip rectangle. /// We must draw something in every part of the clip rectangle (unless fScreen is false), /// because (to avoid flicker drawing selections) we don't erase the window before /// drawing. We do this by stretching the element horizontally, and separately /// erasing the areas between elements (and before and after them). /// </summary> /// <param name="gr">graphics object to draw with</param> /// <param name="rectClip">rectangle to draw in (in target device pixels)</param> /// <param name="zoom">The zoom.</param> /// <param name="fScreen">true if drawing to screen, false for printers</param> /// ------------------------------------------------------------------------------------ internal void Draw(Graphics gr, Rectangle rectClip, float zoom, bool fScreen) { CheckDisposed(); Debug.Assert(!m_fBroken); float targetDpiX = gr.DpiX; float targetDpiY = gr.DpiY; int dpiXScreen = (int)(targetDpiX * zoom); int dpiYScreen = (int)(targetDpiY * zoom); Point unprintableAdjustment = new Point(0, 0); Point gutterAdjustment = new Point(0, 0); // for printing, calculate the amount of space to adjust each object placement by // to account for the unprintable area of a page. NOTE: this must be done before // getting the hDC because the Graphics object will then be locked. int autoscrollY = PubControl.AutoScrollPosition.Y; if (!fScreen) { unprintableAdjustment.X = -(rectClip.Width - (int)(gr.VisibleClipBounds.Width * targetDpiX) / 100) / 2; unprintableAdjustment.Y = -(rectClip.Height - (int)(gr.VisibleClipBounds.Height * (int)targetDpiY) / 100) / 2; // Make an adjustment for the gutter. if (PubControl.Publication.BindingEdge == BindingSide.Top) { if (PageNumber % 2 == 1 || PubControl.Publication.SheetLayout == MultiPageLayout.Simplex) { // Top gutter only comes into play if we're printing the page whose // top edge is the binding edge (i.e., normally the odd pages) gutterAdjustment.Y = (int)(PubControl.Publication.GutterMargin * targetDpiY / MiscUtils.kdzmpInch); } else if (PubControl.Publication.SheetLayout == MultiPageLayout.Duplex) { // This calculation attempts to deal with printing the "backside" page when // doing duplex. If the logical page size is smaller than the physical sheet size // onto which we're printing, we need to shift the printing origin so the backside // lines up with the frontside. // TODO: We're still off by a little. gutterAdjustment.Y = rectClip.Height - (int)((PubControl.Publication.PageHeight + PubControl.Publication.GutterMargin) * targetDpiY / MiscUtils.kdzmpInch); } } else { if ((PageNumber % 2 == 1 && PubControl.Publication.BindingEdge == BindingSide.Left) || (PageNumber % 2 == 0 && PubControl.Publication.BindingEdge == BindingSide.Right) || PubControl.Publication.SheetLayout == MultiPageLayout.Simplex || PubControl.Publication.PageWidth == 0) // 0 => full-page { // Side gutter only comes into play if we're printing the page whose // left edge is the binding edge (i.e., normally the odd pages) gutterAdjustment.X = (int)(PubControl.Publication.GutterMargin * targetDpiX / MiscUtils.kdzmpInch); } else if (PubControl.Publication.SheetLayout == MultiPageLayout.Duplex) { // This calculation attempts to deal with printing the "backside" page when // doing duplex. If the logical page size is smaller than the physical sheet size // onto which we're printing, we need to shift the printing origin so the backside // lines up with the frontside. // TODO: We're still off by a little, however not we're off by the same amount as // Microsoft Word when doing duplex, justified printing. We may need to provide // a printer-specific adjustment. gutterAdjustment.X = rectClip.Width - (int)((PubControl.Publication.PageWidth + PubControl.Publication.GutterMargin) * targetDpiX / MiscUtils.kdzmpInch); } } autoscrollY = 0; } int indexOfThisPage = PubControl.IndexOfPage(this); int bottomOfPage = PubControl.PageHeightPlusGapInScreenPixels * (indexOfThisPage + 1) - PubControl.Gap + autoscrollY; if (!fScreen) bottomOfPage = Int32.MaxValue; List<Rectangle> backgroundRects = new List<Rectangle>(); // This is the bottom of the area drawn or erased by the previous element. // to begin with, it can be the very top of the page. int bottomPrev = PubControl.PageHeightPlusGapInScreenPixels * (indexOfThisPage) + autoscrollY; if (!fScreen) bottomPrev = 0; IntPtr hdc = gr.GetHdc(); IVwGraphicsWin32 vg = VwGraphicsWin32Class.Create(); vg.Initialize(hdc); try { if (fScreen) { vg.XUnitsPerInch = dpiXScreen; vg.YUnitsPerInch = dpiYScreen; } IVwDrawRootBuffered vdrb = VwDrawRootBufferedClass.Create(); uint rgbBackColor = ColorUtil.ConvertColorToBGR(PubControl.BackColor); Debug.Assert(PageElements != null); foreach (PageElement element in PageElements) { IVwRootBox rootb = (IVwRootBox)element.m_stream; // Compute the part of this element that intersects the ClipRect. Rectangle rectElement = element.PositionInLayout(indexOfThisPage, PubControl, targetDpiX, targetDpiY, unprintableAdjustment, gutterAdjustment, fScreen); if (fScreen) { // If drawing on the screen expand this to the width of the clip rectangle Rectangle rectClipElt = GetElementClipBounds(element, rectElement); // If it doesn't intersect the clip rect skip this element. if (!rectClipElt.IntersectsWith(rectClip)) continue; rectClipElt.Intersect(rectClip); // We need to draw the space between the bottom of the previous element // and the top of the current element with the background color. if (bottomPrev < rectClipElt.Top) { Rectangle rectErase = new Rectangle(rectClip.X, bottomPrev, rectClip.Width, rectClipElt.Top - bottomPrev); if (rectErase.IntersectsWith(rectClip)) { rectErase.Intersect(rectClip); // Unfortunately we can't erase the background right away // because we obtained the HDC above. Need to do it later. backgroundRects.Add(rectErase); } } bottomPrev = rectClipElt.Bottom; // It just works! // The origin of this rectangle is the offset from the origin of this rootbox's // data to the origin of this element (in printer pixels). Rectangle rectSrc = new Rectangle(0, element.OffsetToTopPageBoundary - element.OverlapWithPreviousElement, (int)(PubControl.DpiXPrinter), (int)(PubControl.DpiYPrinter)); // The origin of this rectangle is the offset from the origin of this element // to the origin of the clip rectangle (the part of the rc that // actually pertains to this element) (in screen pixels) Rectangle rectDst = new Rectangle(rectElement.Left - rectClipElt.Left, rectElement.Top - rectClipElt.Top, dpiXScreen, dpiYScreen); // By "adding" the origins of the source and destination rectangles together // (each in its respective context, printer or screen), we get the overall // offset to the bit of data we actually want to draw in the clip rectangle. vdrb.DrawTheRootAt(rootb, hdc, rectClipElt, rgbBackColor, true, vg, rectSrc, rectDst, element.OffsetToTopPageBoundary, element.ColumnHeight); #if DEBUG #if _DEBUG_SHOW_BOX vg.ForeColor = (int)ColorUtil.ConvertColorToBGR(Color.Red); vg.DrawLine(rectElement.Left, rectElement.Top, rectElement.Left, rectElement.Bottom); vg.DrawLine(rectElement.Left, rectElement.Top, rectElement.Right, rectElement.Top); vg.DrawLine(rectElement.Right, rectElement.Top, rectElement.Right, rectElement.Bottom); vg.DrawLine(rectElement.Left, rectElement.Bottom, rectElement.Right, rectElement.Bottom); #endif #endif } else { // This version is for the printer. // (a) it uses a simpler interface for drawing, since it doesn't need to // fill in the background first, nor use double-buffering, nor do clipping. // (b) therefore it doesn't create a clip rectangle. // (c) but, it does need a dst rectangle at printer resolution. // (d) because we aren't drawing just in a clip rectangle, but the whole page, // the offset of each element is just the page element offsets. // As well as being much faster, this doesn't try to paint the page with the // window background color, and creates mdi files around 35 times smaller. // The origin of this rectangle is the offset from the origin of this rootbox's // data to the origin of this element (in printer pixels). Rectangle rectSrc = new Rectangle(0, element.OffsetToTopPageBoundary, (int)(PubControl.DpiXPrinter), (int)(PubControl.DpiYPrinter)); // The origin of this rectangle is the offset from the origin of this element // to the origin of the clip rectangle (the part of the rc that // actually pertains to this element) (in screen pixels) Rectangle rectDst = new Rectangle(rectElement.Left, rectElement.Top, (int)(PubControl.DpiXPrinter), (int)(PubControl.DpiYPrinter)); rootb.DrawRoot2(vg, rectSrc, rectDst, false, element.OffsetToTopPageBoundary, element.ColumnHeight); } try { rootb.DrawingErrors(); } catch /*(Exception ex)*/ { //TODO: GiveDrawErrMsg(ex, false); } } } finally { vg.ReleaseDC(); gr.ReleaseHdc(hdc); } if (fScreen) { // We also need to erase the background between the bottom of the last // element and the bottom of the page if (bottomPrev < bottomOfPage) { Rectangle rectErase = new Rectangle(rectClip.X, bottomPrev, rectClip.Width, bottomOfPage - bottomPrev); if (rectErase.IntersectsWith(rectClip)) { rectErase.Intersect(rectClip); backgroundRects.Add(rectErase); } } if (backgroundRects.Count > 0) gr.FillRectangles(new SolidBrush(PubControl.BackColor), backgroundRects.ToArray()); // Draw the gap to show page break. int bottomOfPageInDoc = PubControl.PageHeightPlusGapInScreenPixels * (indexOfThisPage + 1) - PubControl.Gap; Rectangle rectGap = new Rectangle(0, bottomOfPage, PubControl.PageWidth * dpiXScreen / MiscUtils.kdzmpInch, PubControl.Gap); gr.FillRectangle(new SolidBrush(Color.FromKnownColor(KnownColor.ControlDark)), rectGap); // Todo: draw the 3d effect around the page. } // Make a separator line above subordinate streams according to publication settings. foreach (PageElement element in PageElements) { if (!element.IsSubordinateStream || PubControl == null || PubControl.Publication.FootnoteSepWidth == 0) { continue; } // Compute the part of this element that intersects the ClipRect. Rectangle rectElement = element.PositionInLayout(indexOfThisPage, PubControl, targetDpiX, targetDpiY, unprintableAdjustment, gutterAdjustment, fScreen); int dpiX = fScreen ? dpiXScreen : (int)(PubControl.DpiXPrinter); int dpiY = fScreen ? dpiYScreen : (int)(PubControl.DpiYPrinter); Rectangle rectDst = new Rectangle(rectElement.Left, rectElement.Top + 1, dpiX, dpiY); AddSeparatorForDependentStream(gr, element, rectElement, rectDst); } // m_fReadyForDrawing = false; }
public static void DrawHeader(Graphics g, Rectangle bounds, int headerState) { Rectangle rect = Rectangle.Truncate(g.ClipBounds); if (2 == headerState) { VisualStyleRenderer.SetParameters(DataGridViewColumnHeaderCell.HeaderElement); Rectangle clipRectangle = new Rectangle(bounds.Left, bounds.Bottom - 2, 2, 2); clipRectangle.Intersect(rect); VisualStyleRenderer.DrawBackground(g, bounds, clipRectangle); clipRectangle = new Rectangle(bounds.Right - 2, bounds.Bottom - 2, 2, 2); clipRectangle.Intersect(rect); VisualStyleRenderer.DrawBackground(g, bounds, clipRectangle); } VisualStyleRenderer.SetParameters(DataGridViewColumnHeaderCell.HeaderElement.ClassName, DataGridViewColumnHeaderCell.HeaderElement.Part, headerState); VisualStyleRenderer.DrawBackground(g, bounds, rect); }
protected override void OnPaint(PaintEventArgs e) { Region clippingRegion = e.Graphics.Clip; TimeSpan time = TimeSpan.FromHours(EpgControl.EpgHoursOffset); int left = 0; const int step = 15; for (int count = 0; count < (24 * 60) / step; count++) { TimeSpan nextTime = time.Add(TimeSpan.FromMinutes(step)); int nextLeft = EpgTimeControl.GetTimeCursorPosition(nextTime, 0); Rectangle visibleRectangle = new Rectangle(left - 1, 0, nextLeft - left + 1, this.Height); visibleRectangle.Intersect(e.ClipRectangle); Region cellRegion = new Region(visibleRectangle); cellRegion.Intersect(clippingRegion); if (!cellRegion.IsEmpty(e.Graphics)) { int lineLeft = Math.Max(0, left - 1); e.Graphics.DrawLine(_epgBorderPen, lineLeft, 0, lineLeft, this.Height - 1); string timeText = EpgTimeControl.GetTimeString(time); e.Graphics.DrawString(timeText, _timeFont, _timeBrush, lineLeft + 1, 2); } left = nextLeft; time = nextTime; } if (this.CursorAtTime.HasValue) { int position = EpgTimeControl.GetTimeCursorPosition(_cursorAtTime.Value, -1); e.Graphics.DrawLine(_cursorPen, position, 0, position, this.Height - 1); e.Graphics.DrawLine(_cursorShadowPen, position + 1, 0, position + 1, this.Height - 1); string timeText = EpgTimeControl.GetTimeString(this.CursorAtTime.Value); SizeF size = e.Graphics.MeasureString(timeText, _cursorFont); e.Graphics.FillRectangle(_cursorBgBrush, position + 2, 1, size.Width, size.Height); e.Graphics.DrawString(timeText, _cursorFont, _cursorBrush, position + 2, 0); } base.OnPaint(e); }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="dce"></param> static private unsafe void _DesktopChange(object sender, DesktopChangeEventArgs dce) { if (streamer.clients.Count > 0) // No one is listening, why bother to process updates { try { lock (streamer.updates.SyncRoot) { if (streamer.updates.Count == 0) { if (numUpdates++ > 5) { // Send the iFrame GCbuf screenbuf = new GCbuf(); #if USE_BITMAP_COMPRESS int ptr = DesktopMirror._bitmapWidth * DesktopMirror._bitmapHeight, num = 0; for (int i = 0; i < ptr; i++) { screenbuf.buf[num++] = 0xFF; } for (int i = 0; i < (ptr * 4); i += 4) { screenbuf.buf[num++] = _mirror.screen[i]; screenbuf.buf[num++] = _mirror.screen[i + 1]; screenbuf.buf[num++] = _mirror.screen[i + 2]; } #else Buffer.BlockCopy(_mirror.screen, 0, screenbuf.buf, 0, _mirror.screen.Length); // for (int i = 0; i < _mirror.screen.Length; i++) // screenbuf.buf[i] = _mirror.screen[i]; #endif screenbuf.Length = _mirror.screen.Length; streamer.updates.Enqueue(new sendUpdate(null, screenbuf, maskX, maskY, maskWidth, maskHeight)); numUpdates = 0; } else { if (maskValid == true) { System.Drawing.Rectangle cur = new System.Drawing.Rectangle(dce.x, dce.y, dce.w, dce.h); System.Drawing.Rectangle mask = new System.Drawing.Rectangle(Program.maskX, Program.maskY, Program.maskWidth, Program.maskHeight); cur.Intersect(mask); if (cur.IsEmpty) { return; } else { streamer.updates.Enqueue(new sendUpdate(null, null, cur.X, cur.Y, cur.Width, cur.Height)); } } else { streamer.updates.Enqueue(new sendUpdate(null, null, dce.x, dce.y, dce.w, dce.h)); } } } else { System.Drawing.Rectangle orig = new System.Drawing.Rectangle(dce.x, dce.y, dce.w, dce.h); if (maskValid == true) { System.Drawing.Rectangle mask = new System.Drawing.Rectangle(Program.maskX, Program.maskY, Program.maskWidth, Program.maskHeight); orig.Intersect(mask); if (orig.IsEmpty) { return; } } for (int i = streamer.updates.Count; i > 0; i--) { sendUpdate upd = (sendUpdate)streamer.updates.Dequeue(); System.Drawing.Rectangle cur = new System.Drawing.Rectangle(upd.x, upd.y, upd.w, upd.h); /* I don't think that I need to do this * if (maskValid == true) { * cur.Intersect(mask); * if (cur.IsEmpty) * continue; * } */ cur.Intersect(orig); if (cur.IsEmpty) { // Move this update to the back of the line? Okay because all pending updates are disjoint streamer.updates.Enqueue(upd); // Moved to the front of the for loop // upd = (sendUpdate)streamer.updates.Dequeue(); } else { cur.X = upd.x; cur.Y = upd.y; cur.Width = upd.w; cur.Height = upd.h; System.Drawing.Rectangle combined = System.Drawing.Rectangle.Union(orig, cur); Boolean anymoreCombine = true; // int count = 0; while (anymoreCombine) { anymoreCombine = false; for (int j = streamer.updates.Count; j > 0; j--) { sendUpdate u = (sendUpdate)streamer.updates.Dequeue(); System.Drawing.Rectangle nxt = new System.Drawing.Rectangle(u.x, u.y, u.w, u.h); /* I don't think that I need this either * if (maskValid == true) { * nxt.Intersect(mask); * if (nxt.IsEmpty) * continue; * } */ nxt.Intersect(combined); if (nxt.IsEmpty) { streamer.updates.Enqueue(u); } else { nxt.X = u.x; nxt.Y = u.y; nxt.Width = u.w; nxt.Height = u.h; combined = System.Drawing.Rectangle.Union(combined, nxt); anymoreCombine = true; Trace.WriteLine("DEBUG: ----"); break; } } } streamer.updates.Enqueue(new sendUpdate(null, null, combined.X, combined.Y, combined.Width, combined.Height)); // Trace.WriteLine("DEBUG: need to make sure that this update does not overlap with prior non-overlapping rectangles"); // Actually don't need to because of the way that Queue's work? return; } } if (maskValid == true) { System.Drawing.Rectangle cur = new System.Drawing.Rectangle(dce.x, dce.y, dce.w, dce.h); System.Drawing.Rectangle mask = new System.Drawing.Rectangle(Program.maskX, Program.maskY, Program.maskWidth, Program.maskHeight); cur.Intersect(mask); if (cur.IsEmpty) { return; } streamer.updates.Enqueue(new sendUpdate(null, null, cur.X, cur.Y, cur.Width, cur.Height)); } else { streamer.updates.Enqueue(new sendUpdate(null, null, dce.x, dce.y, dce.w, dce.h)); } } } } catch (System.IO.IOException) { Trace.WriteLine("DEBUG: An internal Win32 exception is caused by update while creating event handler. Ignoring"); // Environment.Exit(1); } catch (Exception e) { MessageBox.Show("DEBUG: Error while capturing update coordinates " + e.StackTrace); } } }
public void SaveRegion(PdnRegion saveMeRegion, Rectangle saveMeBounds) { BitmapLayer activeLayer = (BitmapLayer)ActiveLayer; if (savedTiles == null) { savedTiles = new BitVector2D( (activeLayer.Width + saveTileGranularity - 1) / saveTileGranularity, (activeLayer.Height + saveTileGranularity - 1) / saveTileGranularity); savedTiles.Clear(false); } Rectangle regionBounds; if (saveMeRegion == null) { regionBounds = saveMeBounds; } else { regionBounds = saveMeRegion.GetBoundsInt(); } Rectangle bounds = Rectangle.Union(regionBounds, saveMeBounds); bounds.Intersect(activeLayer.Bounds); int leftTile = bounds.Left / saveTileGranularity; int topTile = bounds.Top / saveTileGranularity; int rightTile = (bounds.Right - 1) / saveTileGranularity; int bottomTile = (bounds.Bottom - 1) / saveTileGranularity; for (int tileY = topTile; tileY <= bottomTile; ++tileY) { Rectangle rowAccumBounds = Rectangle.Empty; for (int tileX = leftTile; tileX <= rightTile; ++tileX) { if (!savedTiles.Get(tileX, tileY)) { Rectangle tileBounds = new Rectangle(tileX * saveTileGranularity, tileY * saveTileGranularity, saveTileGranularity, saveTileGranularity); tileBounds.Intersect(activeLayer.Bounds); if (rowAccumBounds == Rectangle.Empty) { rowAccumBounds = tileBounds; } else { rowAccumBounds = Rectangle.Union(rowAccumBounds, tileBounds); } savedTiles.Set(tileX, tileY, true); } else { if (rowAccumBounds != Rectangle.Empty) { using (Surface dst = ScratchSurface.CreateWindow(rowAccumBounds), src = activeLayer.Surface.CreateWindow(rowAccumBounds)) { dst.CopySurface(src); } rowAccumBounds = Rectangle.Empty; } } } if (rowAccumBounds != Rectangle.Empty) { using (Surface dst = ScratchSurface.CreateWindow(rowAccumBounds), src = activeLayer.Surface.CreateWindow(rowAccumBounds)) { dst.CopySurface(src); } rowAccumBounds = Rectangle.Empty; } } if (this.saveRegion != null) { this.saveRegion.Dispose(); this.saveRegion = null; } if (saveMeRegion != null) { this.saveRegion = saveMeRegion.Clone(); } }
/// <summary> /// Get skew angle of the provided document image. /// </summary> /// /// <param name="image">Document's unmanaged image to get skew angle of.</param> /// <param name="rect">Image's rectangle to process (used to exclude processing of /// regions, which are not relevant to skew detection).</param> /// /// <returns>Returns document's skew angle. If the returned angle equals to -90, /// then document skew detection has failed.</returns> /// /// <exception cref="UnsupportedImageFormatException">Unsupported pixel format of the source image.</exception> /// public double GetSkewAngle( UnmanagedImage image, Rectangle rect ) { if ( image.PixelFormat != PixelFormat.Format8bppIndexed ) { throw new UnsupportedImageFormatException( "Unsupported pixel format of the source image." ); } // init hough transformation settings InitHoughMap( ); // get source image size int width = image.Width; int height = image.Height; int halfWidth = width / 2; int halfHeight = height / 2; // make sure the specified rectangle recides with the source image rect.Intersect( new Rectangle( 0, 0, width, height ) ); int startX = -halfWidth + rect.Left; int startY = -halfHeight + rect.Top; int stopX = width - halfWidth - ( width - rect.Right ); int stopY = height - halfHeight - ( height - rect.Bottom ) - 1; int offset = image.Stride - rect.Width; // calculate Hough map's width int halfHoughWidth = (int) Math.Sqrt( halfWidth * halfWidth + halfHeight * halfHeight ); int houghWidth = halfHoughWidth * 2; houghMap = new short[houghHeight, houghWidth]; // do the job unsafe { byte* src = (byte*) image.ImageData.ToPointer( ) + rect.Top * image.Stride + rect.Left; byte* srcBelow = src + image.Stride; // for each row for ( int y = startY; y < stopY; y++ ) { // for each pixel for ( int x = startX; x < stopX; x++, src++, srcBelow++ ) { // if current pixel is more black // and pixel below is more white if ( ( *src < 128 ) && ( *srcBelow >= 128 ) ) { // for each Theta value for ( int theta = 0; theta < houghHeight; theta++ ) { int radius = (int) ( cosMap[theta] * x - sinMap[theta] * y ) + halfHoughWidth; if ( ( radius < 0 ) || ( radius >= houghWidth ) ) continue; houghMap[theta, radius]++; } } } src += offset; srcBelow += offset; } } // find max value in Hough map maxMapIntensity = 0; for ( int i = 0; i < houghHeight; i++ ) { for ( int j = 0; j < houghWidth; j++ ) { if ( houghMap[i, j] > maxMapIntensity ) { maxMapIntensity = houghMap[i, j]; } } } CollectLines( (short) ( width / 10 ) ); // get skew angle HoughLine[] hls = this.GetMostIntensiveLines( 5 ); double skewAngle = 0; double sumIntensity = 0; foreach ( HoughLine hl in hls ) { if ( hl.RelativeIntensity > 0.5 ) { skewAngle += ( hl.Theta * hl.RelativeIntensity ); sumIntensity += hl.RelativeIntensity; } } if ( hls.Length > 0 ) skewAngle = skewAngle / sumIntensity; return skewAngle - 90.0; }
protected override List<PointF> CreateShape(List<Point> tracePoints) { Point a = tracePoints[0]; Point b = tracePoints[tracePoints.Count - 1]; Rectangle rect; SelectionDrawModeInfo sdmInfo = AppEnvironment.SelectionDrawModeInfo; switch (sdmInfo.DrawMode) { case SelectionDrawMode.Normal: if ((ModifierKeys & Keys.Shift) != 0) { rect = Utility.PointsToConstrainedRectangle(a, b); } else { rect = Utility.PointsToRectangle(a, b); } break; case SelectionDrawMode.FixedRatio: try { int drawnWidth = b.X - a.X; int drawnHeight = b.Y - a.Y; double drawnWidthScale = (double)drawnWidth / (double)sdmInfo.Width; double drawnWidthSign = Math.Sign(drawnWidthScale); double drawnHeightScale = (double)drawnHeight / (double)sdmInfo.Height; double drawnHeightSign = Math.Sign(drawnHeightScale); double aspect = (double)sdmInfo.Width / (double)sdmInfo.Height; if (drawnWidthScale < drawnHeightScale) { rect = Utility.PointsToRectangle( new Point(a.X, a.Y), new Point(a.X + drawnWidth, a.Y + (int)(drawnHeightSign * Math.Abs((double)drawnWidth / aspect)))); } else { rect = Utility.PointsToRectangle( new Point(a.X, a.Y), new Point(a.X + (int)(drawnWidthSign * Math.Abs((double)drawnHeight * aspect)), a.Y + drawnHeight)); } } catch (ArithmeticException) { rect = new Rectangle(a.X, a.Y, 0, 0); } break; case SelectionDrawMode.FixedSize: double pxWidth = Document.ConvertMeasurement(sdmInfo.Width, sdmInfo.Units, this.Document.DpuUnit, this.Document.DpuX, MeasurementUnit.Pixel); double pxHeight = Document.ConvertMeasurement(sdmInfo.Height, sdmInfo.Units, this.Document.DpuUnit, this.Document.DpuY, MeasurementUnit.Pixel); rect = new Rectangle(b.X, b.Y, (int)pxWidth, (int)pxHeight); break; default: throw new InvalidEnumArgumentException(); } rect.Intersect(DocumentWorkspace.Document.Bounds); List<PointF> shape; if (rect.Width > 0 && rect.Height > 0) { shape = new List<PointF>(5); shape.Add(new PointF(rect.Left, rect.Top)); shape.Add(new PointF(rect.Right, rect.Top)); shape.Add(new PointF(rect.Right, rect.Bottom)); shape.Add(new PointF(rect.Left, rect.Bottom)); shape.Add(shape[0]); } else { shape = new List<PointF>(0); } return shape; }
/// <summary> /// Collect coordinates of none black pixels within specified rectangle of the image. /// </summary> /// /// <param name="rect">Image's rectangle to process.</param> /// /// <returns>Returns list of points, which have other than black color.</returns> /// public List<IntPoint> CollectActivePixels( Rectangle rect ) { List<IntPoint> pixels = new List<IntPoint>( ); int pixelSize = Bitmap.GetPixelFormatSize( pixelFormat ) / 8; // correct rectangle rect.Intersect( new Rectangle( 0, 0, width, height ) ); int startX = rect.X; int startY = rect.Y; int stopX = rect.Right; int stopY = rect.Bottom; unsafe { byte* basePtr = (byte*) imageData.ToPointer( ); if ( ( pixelFormat == PixelFormat.Format16bppGrayScale ) || ( pixelSize > 4 ) ) { int pixelWords = pixelSize >> 1; for ( int y = startY; y < stopY; y++ ) { ushort* ptr = (ushort*) ( basePtr + y * stride + startX * pixelSize ); if ( pixelWords == 1 ) { // grayscale images for ( int x = startX; x < stopX; x++, ptr++ ) { if ( *ptr != 0 ) { pixels.Add( new IntPoint( x, y ) ); } } } else { // color images for ( int x = startX; x < stopX; x++, ptr += pixelWords ) { if ( ( ptr[RGB.R] != 0 ) || ( ptr[RGB.G] != 0 ) || ( ptr[RGB.B] != 0 ) ) { pixels.Add( new IntPoint( x, y ) ); } } } } } else { for ( int y = startY; y < stopY; y++ ) { byte* ptr = basePtr + y * stride + startX * pixelSize; if ( pixelSize == 1 ) { // grayscale images for ( int x = startX; x < stopX; x++, ptr++ ) { if ( *ptr != 0 ) { pixels.Add( new IntPoint( x, y ) ); } } } else { // color images for ( int x = startX; x < stopX; x++, ptr += pixelSize ) { if ( ( ptr[RGB.R] != 0 ) || ( ptr[RGB.G] != 0 ) || ( ptr[RGB.B] != 0 ) ) { pixels.Add( new IntPoint( x, y ) ); } } } } } } return pixels; }