public Line Test(int x, int y, int x2, int y2) { System.Drawing.Rectangle r = new System.Drawing.Rectangle(x, y, x2 - x, y2 - y); Vertex p = new Vertex(0, 0); foreach (Line l in lines) { if (l.Touches(r, ref p)) return l; } return null; }
public static void Run() { // ExStart:AddlnkAnnotation // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Annotations(); Document doc = new Document(); Page pdfPage = doc.Pages.Add(); System.Drawing.Rectangle drect = new System.Drawing.Rectangle(); drect.Height = (int)pdfPage.Rect.Height; drect.Width = (int)pdfPage.Rect.Width; drect.X = 0; drect.Y = 0; Aspose.Pdf.Rectangle arect = Aspose.Pdf.Rectangle.FromRect(drect); ArrayList inkList = new ArrayList(); Aspose.Pdf.Point[] arrpt = new Aspose.Pdf.Point[3]; inkList.Add(arrpt); arrpt[0] = new Aspose.Pdf.Point(100, 800); arrpt[1] = new Aspose.Pdf.Point(200, 800); arrpt[2] = new Aspose.Pdf.Point(200, 700); InkAnnotation ia = new InkAnnotation(pdfPage, arect, inkList); ia.Title = "XXX"; ia.Color = Aspose.Pdf.Color.LightBlue; // (GetColorFromString(stroke.InkColor)); ia.CapStyle = CapStyle.Rounded; Border border = new Border(ia); border.Width = 25; ia.Opacity = 0.5; pdfPage.Annotations.Add(ia); dataDir = dataDir + "AddlnkAnnotation_out.pdf"; // Save output file doc.Save(dataDir); // ExEnd:AddlnkAnnotation Console.WriteLine("\nlnk annotation added successfully.\nFile saved at " + dataDir); }
public static void SomeClass() { var graph = new MSAGL.Drawing.Graph(""); graph.AddEdge("A", "B"); graph.AddEdge("A", "B"); graph.FindNode("A").Attr.FillColor = MSAGL.Drawing.Color.BlanchedAlmond; graph.FindNode("B").Attr.FillColor = MSAGL.Drawing.Color.BurlyWood; var renderer = new MSAGL.GraphViewerGdi.GraphRenderer(graph); renderer.CalculateLayout(); const int width = 50; int height = (int)(graph.Height * (width / graph.Width)); const PixelFormat pixfmt = System.Drawing.Imaging.PixelFormat.Format32bppPArgb; using (var bitmap = new System.Drawing.Bitmap(width, height, pixfmt)) { using (var gfx = System.Drawing.Graphics.FromImage(bitmap)) { gfx.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; gfx.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; gfx.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; var rect = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height); renderer.Render(gfx, rect); bitmap.Save("test.png"); } } }
public static void Draw( SpriteBatch spriteBatch, LevelEd level ) { System.Drawing.Rectangle rect = new System.Drawing.Rectangle( bounds.X, bounds.Y, bounds.Width, bounds.Height ); int gridSpacing; if( Global.Tools.DragSnapAmount < 16 ) gridSpacing = 16; else gridSpacing = Global.Tools.DragSnapAmount; line.Width = GRID_LINE_WIDTH; line.Y = rect.Y; line.Height = rect.Height; for( line.X = rect.X; line.X < rect.Right; line.X += gridSpacing ) spriteBatch.Draw( Global.Pixel, line, GRID_COLOR ); line.X = rect.X; line.Width = rect.Width; line.Height = GRID_LINE_WIDTH; for( line.Y = rect.Y; line.Y < rect.Bottom; line.Y += gridSpacing ) spriteBatch.Draw( Global.Pixel, line, GRID_COLOR ); bounds.Draw( spriteBatch, 2 ); }
public static byte[] CreateAvatar(int sideLength, System.IO.Stream fromStream) { System.IO.MemoryStream ms = new System.IO.MemoryStream(); using (var image = System.Drawing.Image.FromStream(fromStream)) using (var thumbBitmap = new System.Drawing.Bitmap(sideLength, sideLength)) { var a = Math.Min(image.Width, image.Height); var x = (image.Width - a) / 2; var y = (image.Height - a) / 2; using (var thumbGraph = System.Drawing.Graphics.FromImage(thumbBitmap)) { thumbGraph.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; thumbGraph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; thumbGraph.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; var imgRectangle = new System.Drawing.Rectangle(0, 0, sideLength, sideLength); thumbGraph.DrawImage(image, imgRectangle, x, y, a, a, System.Drawing.GraphicsUnit.Pixel); thumbBitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); } } return (ms.ToArray()); }
public static Quaternion GetRotationFromCursor(System.Drawing.Point pt, float fTrackBallRadius) { System.Drawing.Rectangle rc = new System.Drawing.Rectangle(0,0,1024,768); float xpos = (((2.0f * pt.X) / (rc.Right-rc.Left)) - 1); float ypos = (((2.0f * pt.Y) / (rc.Bottom-rc.Top)) - 1); float sz; if (xpos == 0.0f && ypos == 0.0f) return new Quaternion(0.0f, 0.0f, 0.0f, 1.0f); float d2 = (float)Math.Sqrt(xpos*xpos + ypos*ypos); if (d2 < fTrackBallRadius * 0.70710678118654752440) // Inside sphere sz = (float)Math.Sqrt(fTrackBallRadius*fTrackBallRadius - d2*d2); else // On hyperbola sz = (fTrackBallRadius*fTrackBallRadius) / (2.0f*d2); // Get two points on trackball's sphere Vector3 p1 = new Vector3(xpos, ypos, sz); Vector3 p2 = new Vector3(0.0f, 0.0f, fTrackBallRadius); // Get axis of rotation, which is cross product of p1 and p2 Vector3 axis = Vector3.Cross(p1,p2); // Calculate angle for the rotation about that axis float t = Vector3.Length(Vector3.Subtract(p2,p1)) / (2.0f*fTrackBallRadius); if (t > +1.0f) t = +1.0f; if (t < -1.0f) t = -1.0f; float fAngle = (float)(2.0f * Math.Asin(t)); // Convert axis to quaternion return Quaternion.RotationAxis(axis, fAngle); }
public float Compare (FramePixelData a, FramePixelData b) { int minWidth, maxWidth, minHeight, maxHeight; MathUtility.MinMax (a.Width, b.Width, out minWidth, out maxWidth); MathUtility.MinMax (a.Height, b.Height, out minHeight, out maxHeight); var rect = new System.Drawing.Rectangle (0, 0, minWidth, minHeight); long error = 0; int index = 0; for (int y = 0; y < rect.Height; ++y) { for (int x = 0; x < rect.Width; ++x) { error += Delta (a.Data [index], b.Data [index]); index++; } } // FIXME: To temporarily accommodate the differing // resolutions of mobile platforms, we just // ignore all non-overlapping pixels. This // is not ideal, but it's good enough for now. // Mark all out-of-bounds pixels as non-match. //error += PixelArgb.MaxDelta * ((maxWidth * maxHeight) - (minWidth * minHeight)); var dissimilarity = ((float) error / (float) (PixelArgb.MaxDelta * minWidth * minHeight)); // Project dissimilarity to a logarithmic scale. The // difference between having zero pixels wrong and one // pixel wrong is more significant than the difference // betweeen 10,000 wrong and 10,001. return 1.0f - (float) Math.Pow (dissimilarity, 0.5); }
private void SettingsChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (e.PropertyName == "primaryMonitor") { screenBounds = DeviceUtils.DeviceUtil.GetScreen(Settings.Default.primaryMonitor).Bounds; } }
private SharpDX.Direct2D1.Bitmap SDXBitmapFromSysBitmap(WindowRenderTarget device, System.Drawing.Bitmap bitmap) { var sourceArea = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height); var bitmapProperties = new BitmapProperties(new PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, 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 SharpDX.Direct2D1.Bitmap(device, size, tempStream, stride, bitmapProperties); } }
public PeakPattern(Mat inImage, double highThresh = 180.0) { ImageHeight = inImage.Height; ImageWidth = inImage.Width; highThreshold = highThresh; //Should text a smaller bounding box than the peak finding threshold. textRect = ProcessingTools.findTextEdge<Bgr, double>(inImage, new double[] { highThreshold, highThreshold, highThreshold }); //resultList[0] = new BitArray(ImageWidth); Mat croppedImage = new Mat(inImage, textRect); //resultList.Add(ProcessingTools.testLine<Bgr, double>(inImage, new double[] { highThreshold, highThreshold, highThreshold }, // textRect.Top + textRect.Height / 4)); //Console.WriteLine(textRect.Top + textRect.Height / 2); //resultList.Add(ProcessingTools.testLine<Bgr, double>(inImage, new double[] { highThreshold, highThreshold, highThreshold }, // textRect.Top + textRect.Height / 2)); //resultList.Add(ProcessingTools.testLine<Bgr, double>(inImage, new double[] { highThreshold, highThreshold, highThreshold }, // (int)(textRect.Top + textRect.Height * 0.75))); resultList.Add(ProcessingTools.testLine<Bgr, double>(croppedImage, new double[] { highThreshold, highThreshold, highThreshold }, textRect.Height / 4)); // Console.WriteLine(textRect.Top + textRect.Height / 2); resultList.Add(ProcessingTools.testLine<Bgr, double>(croppedImage, new double[] { highThreshold, highThreshold, highThreshold }, textRect.Height / 2)); resultList.Add(ProcessingTools.testLine<Bgr, double>(croppedImage, new double[] { highThreshold, highThreshold, highThreshold }, (int)(textRect.Height * 0.75))); //Console.WriteLine("Disc using lines {0}, {1}, {2}", // textRect.Height / 4, // textRect.Height / 2, // (int)(textRect.Height * 0.75)); }
internal Texture2D huoqupingmutuxing(int x, int y, int w, int h,GraphicsDevice device) { //剪切大小 System.Drawing.Graphics g; //以大小为剪切大小,像素格式为32位RGB创建一个位图对像 System.Drawing.Bitmap bm1 = new System.Drawing.Bitmap(w,h,System.Drawing.Imaging.PixelFormat.Format24bppRgb) ; //定义一个区域 System.Drawing.Rectangle rg = new System.Drawing.Rectangle(x,y,w,h); //要绘制到的位图 g = System.Drawing.Graphics.FromImage(bm1); //将bm内rg所指定的区域绘制到bm1 g.DrawImage(bm, new System.Drawing.Rectangle(0, 0, w, h), rg, System.Drawing.GraphicsUnit.Pixel); return BitmapToTexture2D(device ,bm1); }
protected override void OnUpdateGeometryState() { base.OnUpdateGeometryState(); fGradient.SetVertices(Origin.X, Origin.Y, Frame.Width, Frame.Height); fBorder = new System.Drawing.Rectangle(Origin.X, Origin.Y, Frame.Width, Frame.Height); }
public static void Run() { // ExStart:IdentifyFormFields // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdfFacades_TechnicalArticles(); // First a input pdf file should be assigned Aspose.Pdf.Facades.Form form = new Aspose.Pdf.Facades.Form(dataDir + "FilledForm.pdf"); // Get all field names String[] allfields = form.FieldNames; // Create an array which will hold the location coordinates of Form fields System.Drawing.Rectangle[] box = new System.Drawing.Rectangle[allfields.Length]; for (int i = 0; i < allfields.Length; i++) { // Get the appearance attributes of each field, consequtively FormFieldFacade facade = form.GetFieldFacade(allfields[i]); // Box in FormFieldFacade class holds field's location. box[i] = facade.Box; } form.Save(dataDir + "IdentifyFormFields_1_out.pdf"); Document doc = new Document(dataDir + "FilledForm - 2.pdf"); // Now we need to add a textfield just upon the original one FormEditor editor = new FormEditor(doc); for (int i = 0; i < allfields.Length; i++) { // Add text field beneath every existing form field editor.AddField(FieldType.Text, "TextField" + i, allfields[i], 1, box[i].Left, box[i].Top, box[i].Left + 50, box[i].Top + 10); } // Close the document editor.Save(dataDir + "IdentifyFormFields_out.pdf"); // ExEnd:IdentifyFormFields }
/// <summary> /// Initializes a new DirectXTexture class. /// </summary> /// <param name="bmp">The Bitmap.</param> internal DirectXTexture(System.Drawing.Bitmap bmp) { RawBitmap = (System.Drawing.Bitmap) bmp.Clone(); _width = bmp.Width; _height = bmp.Height; var sourceArea = new Rectangle(0, 0, bmp.Width, bmp.Height); var bitmapProperties = new BitmapProperties( new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied), 96, 96); var size = new Size2(bmp.Width, bmp.Height); int stride = bmp.Width*sizeof (int); using (var tempStream = new DataStream(bmp.Height*stride, true, true)) { BitmapData bitmapData = bmp.LockBits(sourceArea, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); for (int y = 0; y < bmp.Height; y++) { int offset = bitmapData.Stride*y; for (int x = 0; x < bmp.Width; x++) { 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); } } bmp.UnlockBits(bitmapData); tempStream.Position = 0; _bmp = new Bitmap(DirectXHelper.RenderTarget, size, tempStream, stride, bitmapProperties); } }
public void Evaluate(int SpreadMax) { if (this.FOutLayer[0] == null) { this.FOutLayer[0] = new DX11Resource<DX11Layer>(); } if (this.FEnabled[0]) { this.FLayerIn.Sync(); } if (rectangles.Length != SpreadMax) { rectangles = new System.Drawing.Rectangle[SpreadMax]; } for (int i = 0; i < SpreadMax; i++) { int px ,py,sx,sy; px = (int)FInPosition[i].X; py = (int)FInPosition[i].Y; sx = (int)FInSize[i].X; sy = (int)FInSize[i].Y; rectangles[i] = new System.Drawing.Rectangle(px, py, sx, sy); } }
public static void SetPixels(this EmguImage img, Rectangle area, Color[] pixels) { // Area dimensions int xStart = area.X; int xEnd = xStart + area.Width; int yStart = area.Y; int yEnd = yStart + area.Height; // Area checks if (xStart < 0 || xEnd > img.Width || yStart < 0 || yEnd > img.Height) throw new ArgumentOutOfRangeException("area", area, "The are does not fill in the image"); if (area.Width * area.Height != pixels.Length) throw new ArgumentOutOfRangeException("pixels", pixels, "Invalid number of pixels"); // Data, it's faster not to iterate over a property byte[,,] data = img.Data; // Assign color to each pixel for (int y = yStart; y < yEnd; y++) { for (int x = xStart; x < xEnd; x++) { // TEMP: Swap blue and red due to odd bug of Emug.CV int cIdx = (y - yStart) * area.Width + (x - xStart); data[y, x, 0] = (byte)pixels[cIdx].Blue; data[y, x, 1] = (byte)pixels[cIdx].Green; data[y, x, 2] = (byte)pixels[cIdx].Red; data[y, x, 3] = (byte)pixels[cIdx].Alpha; } } }
//------------------------------- internal MyGdiPlusCanvas( int horizontalPageNum, int verticalPageNum, int left, int top, int width, int height) { #if DEBUG debug_canvas_id = dbug_canvasCount + 1; dbug_canvasCount += 1; #endif this.pageNumFlags = (horizontalPageNum << 8) | verticalPageNum; //2. dimension this.left = left; this.top = top; this.right = left + width; this.bottom = top + height; currentClipRect = new System.Drawing.Rectangle(0, 0, width, height); CreateGraphicsFromNativeHdc(width, height); this.gx = System.Drawing.Graphics.FromHdc(win32MemDc.DC); //------------------------------------------------------- //managed object internalPen = new System.Drawing.Pen(System.Drawing.Color.Black); internalSolidBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black); this.StrokeWidth = 1; }
private void add_anchor_window(System.Windows.Forms.Form form) { var application = this.Application; var parent_window = application.ActiveWindow; if (parent_window == null) { return; } if (application.ActiveDocument == null) { return; } object window_states = IVisio.VisWindowStates.visWSFloating | IVisio.VisWindowStates.visWSVisible; object window_types = IVisio.VisWinTypes.visAnchorBarAddon; var displacement = new System.Drawing.Point(50, 100); var window_rect = new System.Drawing.Rectangle(displacement, form.Size); string window_caption = form.Text; var the_anchor_window = VA.Application.UserInterfaceHelper.AddAnchorWindow(parent_window, window_caption, window_states, window_types, window_rect); if (the_anchor_window != null) { VA.Application.UserInterfaceHelper.AttachWindowsForm(the_anchor_window, form); form.Refresh(); } }
public static void Run() { try { // ExStart:DigitallySignature string pbxFile = ""; // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdfFacades_SecuritySignatures(); // Create PdfFileSignature object and bind input and output PDF files PdfFileSignature pdfSign = new PdfFileSignature(); pdfSign.BindPdf(dataDir + "DigitallySign.pdf"); // Create a rectangle for signature location System.Drawing.Rectangle rect = new System.Drawing.Rectangle(100, 100, 200, 100); // Set signature appearance pdfSign.SignatureAppearance = dataDir + "aspose-logo.jpg"; // Create any of the three signature types PKCS1 signature = new PKCS1(pbxFile, "password"); // PKCS#1 or pdfSign.Sign(1, "Signature Reason", "Contact", "Location", true, rect, signature); // Save output PDF file pdfSign.Save(dataDir + "DigitallySignature_out.pdf"); // ExEnd:DigitallySignature } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public CursorPositionHelper() { smoothingBuffer = new SmoothingBuffer(Settings.Default.pointer_positionSmoothing); screenBounds = DeviceUtils.DeviceUtil.GetScreen(Settings.Default.primaryMonitor).Bounds; Settings.Default.PropertyChanged += SettingsChanged; SystemEvents.DisplaySettingsChanged += SystemEvents_DisplaySettingsChanged; }
/// <summary> /// Creates a new roofing section rectangle /// </summary> /// <param name="rect">The bounds of the rectangle</param> /// <param name="goesUp">Specifies the orientation of the rectangle</param> /// <param name="tent">Specifies that the rectangle is tent shaped</param> /// <param name="sloped">Specifies that the rectangle is sloped (half roof)</param> /// <param name="slope">The slope side if the piece is sloped</param> public RoofRect( System.Drawing.Rectangle rect, bool goesUp, bool tent, bool sloped, Slope slope ) { m_Rectangle = rect; m_GoesUp = goesUp; m_Tent = tent; m_Sloped = sloped; m_Slope = slope; }
public static System.Drawing.Rectangle GetWindowRect(this IVisio.Window window) { // MSDN: http://msdn.microsoft.com/en-us/library/office/ms367542(v=office.14).aspx int left, top, height, width; window.GetWindowRect(out left, out top, out width, out height); var r = new System.Drawing.Rectangle(left, top, width, height); return r; }
public void Draw(Graphics g,Point p) { SysPoint sysp=p.toSysPoint(32); SysRectangle dst=new SysRectangle(sysp.X,sysp.Y,spec.frames[frame].Width,spec.frames[frame].Height); g.DrawImage(spec.image, spec.frames[frame],dst); }
public virtual System.Drawing.Rectangle addImage(ImageInfo image) { int w = image.width; int h = image.height; if (cacheImage.Format != image.format) return System.Drawing.Rectangle.Empty; if (rowX + w > width) { top += rowHeight; rowHeight = 0; rowX = 0; } if (top + h > height) { if (h > height) return System.Drawing.Rectangle.Empty; top = 0; rowX = 0; rowHeight = h; System.Collections.IEnumerator itr = oldGlyphList.listIterator(); //UPGRADE_TODO: Method 'java.util.ListIterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1073_javautilListIteratorhasNext_3"' while (itr.MoveNext()) { //UPGRADE_TODO: Method 'java.util.ListIterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1073_javautilListIteratornext_3"' ((System.Drawing.Rectangle) itr.Current).Width = - 1; } oldGlyphList = glyphList; //UPGRADE_ISSUE: The following fragment of code could not be parsed and was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1156_3"' glyphList = new LinkedList < Rectangle >(); } if (h > rowHeight) rowHeight = h; System.Collections.IEnumerator itr2 = oldGlyphList.listIterator(); //UPGRADE_TODO: Method 'java.util.ListIterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1073_javautilListIteratorhasNext_3"' while (itr2.MoveNext()) { //UPGRADE_TODO: Method 'java.util.ListIterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1073_javautilListIteratornext_3"' System.Drawing.Rectangle r = (System.Drawing.Rectangle) itr2.Current; if (r.Y >= top + rowHeight) break; r.Width = - 1; //UPGRADE_ISSUE: Method 'java.util.ListIterator.remove' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javautilListIteratorremove_3"' itr2.remove(); } System.Drawing.Rectangle r2 = new System.Drawing.Rectangle(rowX, top, w, h); rowX += w; glyphList.addLast(r2); cacheImage.write(r2.X, r2.Y, r2.Width, r2.Height, image.data, image.format); return r2; }
/// <summary> /// Stream to file /// </summary> /// <param name="inputStream"></param> /// <param name="outputFile"></param> /// <param name="fileMode"></param> /// <param name="sourceRectangle"></param> /// <returns></returns> public static string StreamToFile(Stream inputStream, string outputFile, FileMode fileMode, DocumentFormat.OpenXml.Drawing.SourceRectangle sourceRectangle) { try { if (inputStream == null) throw new ArgumentNullException("inputStream"); if (String.IsNullOrEmpty(outputFile)) throw new ArgumentException("Argument null or empty.", "outputFile"); if (Path.GetExtension(outputFile).ToLower() == ".emf" || Path.GetExtension(outputFile).ToLower() == ".wmf") { System.Drawing.Imaging.Metafile emf = new System.Drawing.Imaging.Metafile(inputStream); System.Drawing.Rectangle cropRectangle; double leftPercentage = (sourceRectangle != null && sourceRectangle.Left != null) ? ToPercentage(sourceRectangle.Left.Value) : 0; double topPercentage = (sourceRectangle != null && sourceRectangle.Top != null) ? ToPercentage(sourceRectangle.Top.Value) : 0; double rightPercentage = (sourceRectangle != null && sourceRectangle.Left != null) ? ToPercentage(sourceRectangle.Right.Value) : 0; double bottomPercentage = (sourceRectangle != null && sourceRectangle.Left != null) ? ToPercentage(sourceRectangle.Bottom.Value) : 0; cropRectangle = new System.Drawing.Rectangle( (int)(emf.Width * leftPercentage), (int)(emf.Height * topPercentage), (int)(emf.Width - emf.Width * (leftPercentage + rightPercentage)), (int)(emf.Height - emf.Height * (bottomPercentage + topPercentage))); System.Drawing.Bitmap newBmp = new System.Drawing.Bitmap(cropRectangle.Width, cropRectangle.Height); using (System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(newBmp)) { graphic.Clear(System.Drawing.Color.White); graphic.DrawImage(emf, new System.Drawing.Rectangle(0, 0, cropRectangle.Width, cropRectangle.Height), cropRectangle, System.Drawing.GraphicsUnit.Pixel); } outputFile = outputFile.Replace(".emf", ".jpg"); newBmp.Save(outputFile, System.Drawing.Imaging.ImageFormat.Jpeg); return outputFile; } else { if (!File.Exists(outputFile)) { using (FileStream outputStream = new FileStream(outputFile, fileMode, FileAccess.Write)) { int cnt = 0; const int LEN = 4096; byte[] buffer = new byte[LEN]; while ((cnt = inputStream.Read(buffer, 0, LEN)) != 0) outputStream.Write(buffer, 0, cnt); } } return outputFile; } } catch (Exception ex) { throw ex; } }
internal Window(System.IntPtr hwnd, System.Drawing.Rectangle WindowRect, System.Drawing.Rectangle ClientRect, string WindowText, string ClassName) { this.m_hwnd = hwnd; this.m_WindowRect = WindowRect; this.m_ClientRect = ClientRect; this.m_WindowText = WindowText; this.m_ClassName = ClassName; }
//UPGRADE_NOTE: ref keyword was added to struct-type parameters. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1303'" public virtual void render(NuGraphics3D g3d, ref System.Drawing.Rectangle rectClip, Frame frame, int displayModelIndex, Shape shape) { this.g3d = g3d; this.rectClip = rectClip; this.frame = frame; this.displayModelIndex = displayModelIndex; this.shape = shape; render(); }
public static System.Drawing.Rectangle Rect(System.Drawing.RectangleF rect) { var new_rect = new System.Drawing.Rectangle(); new_rect.X = (int) rect.X; new_rect.Y = (int) rect.Y; new_rect.Width = (int) rect.Width; new_rect.Height = (int) rect.Height; return new_rect; }
public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap bmp) { var rect = new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height); var bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppRgb); int bufferSize = bmpData.Stride * bmp.Height; var bms = new System.Windows.Media.Imaging.WriteableBitmap(bmp.Width, bmp.Height, bmp.HorizontalResolution, bmp.VerticalResolution, PixelFormats.Bgr32, null); bms.WritePixels(new Int32Rect(0, 0, bmp.Width, bmp.Height), bmpData.Scan0, bufferSize, bmpData.Stride); bmp.UnlockBits(bmpData); return bms; }
public static System.Drawing.Rectangle GetRectangle(string strRect) { //Standardize the string to split coordinates by comma strRect = strRect.Replace('x', ','); strRect = strRect.Replace('/', ','); strRect = strRect.Replace(':', ','); string[] aryRect = strRect.Split(','); System.Drawing.Rectangle objRect = new System.Drawing.Rectangle(int.Parse(aryRect[0]), int.Parse(aryRect[1]), int.Parse(aryRect[2]), int.Parse(aryRect[3])); return objRect; }
/// <summary> /// Takes an Ink.Stroke and outputs an internal representation that can /// then be output to an XML file /// </summary> /// <param name="inkStroke">Ink.Stroke which will have extracted from it the information necessary to store a Stroke in MIT XML.</param> /// <param name="transf">Transformation matrix to shift the stroke by</param> /// <param name="shift">Boolean for if we should shift by the transformation matrix</param> /// <returns>PointsAndShape object that stores the extracted information.</returns> public static Sketch.Stroke StripStrokeData(Microsoft.Ink.Stroke inkStroke, Matrix transf, bool shift) { int i; int length; // Get the timestamp for the function using an undocumented GUID (Microsoft.Ink.StrokeProperty.TimeID) to // get the time as a byte array, which we then convert to a long ulong theTime; if (inkStroke.ExtendedProperties[Microsoft.Ink.StrokeProperty.TimeID] != null) { byte[] timeBits = inkStroke.ExtendedProperties[Microsoft.Ink.StrokeProperty.TimeID].Data as byte[]; // Filetime format ulong fileTime = BitConverter.ToUInt64(timeBits, 0); // MIT time format theTime = (fileTime - 116444736000000000) / 10000; //string time = theTime.ToString(); } else { theTime = (ulong)System.DateTime.Now.Ticks; } // Grab X and Y int[] xData = inkStroke.GetPacketValuesByProperty(Microsoft.Ink.PacketProperty.X); int[] yData = inkStroke.GetPacketValuesByProperty(Microsoft.Ink.PacketProperty.Y); if (shift) { // Shift X and Y according to transformation matrix System.Drawing.Point[] pointData = new System.Drawing.Point[xData.Length]; length = xData.Length; for (i = 0; i < length; i++) { pointData[i] = new System.Drawing.Point(xData[i], yData[i]); } transf.TransformPoints(pointData); //Console.WriteLine("x: " + (pointData[0].X - xData[0]) + " y: " + (pointData[0].Y - yData[0])); for (i = 0; i < length; i++) { xData[i] = pointData[i].X; yData[i] = pointData[i].Y; } } Microsoft.Ink.DrawingAttributes drawingAttributes = inkStroke.DrawingAttributes; System.Drawing.Rectangle boundingBox = inkStroke.GetBoundingBox(); // Grab the color int color = drawingAttributes.Color.ToArgb(); // THIS IS DRAWING POINT (PENTIP) HEIGHT AND WIDTH... WE DONT HAVE ANYWHERE TO PUT IT... //string height = inkStroke.DrawingAttributes.Height.ToString(); //string width = inkStroke.DrawingAttributes.Width.ToString(); // Grab height and width of total stroke float height = boundingBox.Height; float width = boundingBox.Width; // Grab penTip string penTip = drawingAttributes.PenTip.ToString(); // Grab raster string raster = drawingAttributes.RasterOperation.ToString(); float x = Convert.ToSingle(boundingBox.X); float y = Convert.ToSingle(boundingBox.Y); //float leftx = Convert.ToSingle(boundingBox.Left); //float topy = Convert.ToSingle(boundingBox.Top); // If the pressure data is included take it, otherwise set to 255/2's int[] pressureData; if (IsPropertyIncluded(inkStroke, Microsoft.Ink.PacketProperty.NormalPressure)) { pressureData = inkStroke.GetPacketValuesByProperty(Microsoft.Ink.PacketProperty.NormalPressure); } else { pressureData = new int[xData.Length]; length = pressureData.Length; for (i = 0; i < length; ++i) { pressureData[i] = (255 - 0) / 2; } } // If the time data is included take it, otherwise set to the timestamp plus and increment ulong[] adjustedTime = new ulong[xData.Length]; int[] timerTick; if (IsPropertyIncluded(inkStroke, Microsoft.Ink.PacketProperty.TimerTick)) { timerTick = inkStroke.GetPacketValuesByProperty(Microsoft.Ink.PacketProperty.TimerTick); length = timerTick.Length; for (i = 0; i < length; i++) { // This may be incorrect, we never encountered this because Microsoft Journal doesn't save TimerTick data. // We know that the timestamp of a stroke is made when the pen is lifted. // Add the time of the stroke to each offset adjustedTime[i] = theTime + (ulong)timerTick[i] * 10000; } } else { timerTick = new int[xData.Length]; length = timerTick.Length; for (i = 0; i < length; i++) { // We believe this to be the standard sample rate. The multiplication by 1,000 is to convert from // seconds to milliseconds. // // Our time is in the form of milliseconds since Jan 1, 1970 // // NOTE: The timestamp for the stroke is made WHEN THE PEN IS LIFTED adjustedTime[i] = theTime - (ulong)((1 / SAMPLE_RATE * 1000) * (length - i)); } } // Create the array of ID's as new Guid's Guid[] idData = new Guid[xData.Length]; length = idData.Length; for (i = 0; i < length; i++) { idData[i] = Guid.NewGuid(); } // Create the internal representation Sketch.Stroke converterStroke = new Sketch.Stroke(); converterStroke.XmlAttrs.Id = System.Guid.NewGuid(); converterStroke.XmlAttrs.Name = "stroke"; converterStroke.XmlAttrs.Time = (ulong)theTime; converterStroke.XmlAttrs.Type = "stroke"; converterStroke.XmlAttrs.Source = "Converter"; Sketch.Substroke substroke = new Sketch.Substroke(); substroke.XmlAttrs.Id = System.Guid.NewGuid(); substroke.XmlAttrs.Name = "substroke"; substroke.XmlAttrs.Time = theTime; substroke.XmlAttrs.Type = "substroke"; substroke.XmlAttrs.Color = color; substroke.XmlAttrs.Height = height; substroke.XmlAttrs.Width = width; substroke.XmlAttrs.PenTip = penTip; substroke.XmlAttrs.Raster = raster; substroke.XmlAttrs.X = x; substroke.XmlAttrs.Y = y; //substroke.XmlAttrs.LeftX = leftx; //substroke.XmlAttrs.TopY = topy; substroke.XmlAttrs.Source = "ConverterJnt"; substroke.XmlAttrs.Start = idData[0]; substroke.XmlAttrs.End = idData[idData.Length - 1]; // Add all of the points to the stroke length = inkStroke.PacketCount; for (i = 0; i < length; i++) { Sketch.Point toAdd = new Sketch.Point(); toAdd.XmlAttrs.Name = "point"; toAdd.XmlAttrs.X = Convert.ToSingle(xData[i]); toAdd.XmlAttrs.Y = Convert.ToSingle(yData[i]); toAdd.XmlAttrs.Pressure = Convert.ToUInt16(pressureData[i]); toAdd.XmlAttrs.Time = Convert.ToUInt64(adjustedTime[i]); toAdd.XmlAttrs.Id = idData[i]; substroke.AddPoint(toAdd); } converterStroke.AddSubstroke(substroke); return(converterStroke); }
public static Screen GetCurrentScreen(Window window) { var parentArea = new System.Drawing.Rectangle((int)window.Left, (int)window.Top, (int)window.Width, (int)window.Height); return(Screen.FromRectangle(parentArea)); }
/// <summary> /// Adds the tab border. /// </summary> /// <param name="path">The path.</param> /// <param name="tabBounds">The tab bounds.</param> public override void AddTabBorder(System.Drawing.Drawing2D.GraphicsPath path, System.Drawing.Rectangle tabBounds) { }
private void DrawMonitors() { var monitorBounds = new List <System.Drawing.Rectangle>(); for (var i = 0; i < _monitorNames.Count; i++) { monitorBounds.Add(ScreenBoundsHelper.GetScreenBounds(i)); } var minX = monitorBounds.Min(bounds => bounds.X); var minY = monitorBounds.Min(bounds => bounds.Y); //Normalize all X and Y coordinates such that the left most bottom monitor start at 0,0 for (var i = 0; i < monitorBounds.Count; i++) { var rectangle = monitorBounds[i]; var x = rectangle.X; if (minX > 0) { x = rectangle.X - minX; } else if (minX < 0) { x = rectangle.X + Math.Abs(minX); } var y = rectangle.Y; if (minY > 0) { y = rectangle.Y - minY; } else if (minY < 0) { y = rectangle.Y + Math.Abs(minY); } monitorBounds[i] = new System.Drawing.Rectangle(x, y, rectangle.Width, rectangle.Height); } var maxMonitorWidth = monitorBounds.Max(bounds => bounds.X + bounds.Width); var maxMonitorHeight = monitorBounds.Max(bounds => bounds.Y + bounds.Height); var scale = Math.Max(maxMonitorWidth / MonitorCanvas.Width, maxMonitorHeight / MonitorCanvas.Height); for (var i = 0; i < monitorBounds.Count; i++) { //Draw a polygon in the shape of the monitor, scaled down var polygon = new Polygon(); var scaledX = monitorBounds[i].X / scale; var scaledY = monitorBounds[i].Y / scale; var scaledXWidth = (monitorBounds[i].X + monitorBounds[i].Width) / scale; var scaledYHeight = (monitorBounds[i].Y + monitorBounds[i].Height) / scale; polygon.Points.Add(new System.Windows.Point(scaledX, scaledY)); //Left top polygon.Points.Add(new System.Windows.Point(scaledX, scaledYHeight)); //Left bottom polygon.Points.Add(new System.Windows.Point(scaledXWidth, scaledYHeight)); //Right bottom polygon.Points.Add(new System.Windows.Point(scaledXWidth, scaledY)); //Right top polygon.Stroke = Brushes.LightGray; polygon.StrokeThickness = 3; MonitorCanvas.Children.Add(polygon); //Draw the number of the monitor var textBlock = new TextBlock(); textBlock.Text = (i + 1).ToString(); //+ 1 since i starts at 0 textBlock.Foreground = Brushes.LightGray; textBlock.FontSize = 20; Canvas.SetLeft(textBlock, ((monitorBounds[i].X + (monitorBounds[i].Width / 2)) / scale) - 5); //-5 and -15 to position the numbers more to the center Canvas.SetTop(textBlock, ((monitorBounds[i].Y + (monitorBounds[i].Height / 2)) / scale) - 15); MonitorCanvas.Children.Add(textBlock); } }
protected void btnUpload_Click(object sender, EventArgs e) { //Dosya yükleme kodu internetten alınmıştır. // If the user has selected a file if (FileUpload1.HasFile) { // Get the file extension string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName); if (fileExtension.ToLower() != ".png" && fileExtension.ToLower() != ".jpg" && fileExtension.ToLower() != ".jpeg") { lblMessage.ForeColor = System.Drawing.Color.Red; lblMessage.Text = "Only files with .jpeg, .png and .jpg extension are allowed"; } else { // Get the file size int fileSize = FileUpload1.PostedFile.ContentLength; // If file size is greater than 2 MB if (fileSize > 2097152) { lblMessage.ForeColor = System.Drawing.Color.Red; lblMessage.Text = "File size cannot be greater than 2 MB"; } else { // Upload the file FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + FileUpload1.FileName)); lblMessage.ForeColor = System.Drawing.Color.Green; lblMessage.Text = "File uploaded successfully"; adress = Server.MapPath("~/Uploads/" + FileUpload1.FileName); System.IO.Stream stream = FileUpload1.PostedFile.InputStream; System.Drawing.Image image = System.Drawing.Image.FromStream(stream); int height = image.Height; int width = image.Width; var ocr = new IronOcr.AutoOcr() { ReadBarCodes = false }; var Area = new System.Drawing.Rectangle() { X = 0, Y = height * 3 / 4, Width = width, Height = height }; String words = ocr.Read(adress, Area).ToString(); String[] words_isbn = words.Split(' '); String isbn = ""; int i = 0, i_keep = 0; for (i = 0; i < words_isbn.Length; i++) { if (words_isbn[i].Contains("SBN") || words_isbn[i].Equals("ISBN") || words_isbn[i].Equals("İSBN") || words_isbn[i].Equals("ısbn") || words_isbn[i].Equals("isbn") || words_isbn[i].Equals("|SBN") || words_isbn[i].Equals("lSBN") || words_isbn[i].Equals("LSBN")) { i_keep = i; } } if (i_keep == 0 && (words_isbn[i_keep].Contains("ISBN") == false || words_isbn[i_keep].Contains("SBN") == false)) { for (i = i_keep; i < words_isbn.Length; i++) { isbn += words_isbn[i]; } } else if (words_isbn[i_keep].Contains("ISBN") && words_isbn[i_keep].All(char.IsDigit)) { int index = words_isbn[i_keep].IndexOf('I'); for (i = index; i < words_isbn[i_keep].Length; i++) { isbn += words_isbn[i_keep][i]; } for (i = i_keep + 1; i < words_isbn.Length; i++) { isbn += words_isbn[i]; } } else if (words_isbn[i_keep].Contains("ISBN") && words_isbn[i_keep].All(char.IsDigit) == false) { if (words_isbn.Length < i_keep + 8) { for (i = i_keep + 1; i < words_isbn.Length; i++) { isbn += words_isbn[i]; } } else { for (i = i_keep + 1; i < i_keep + 8; i++) { isbn += words_isbn[i]; } } } Regex regex = new Regex("[^0-9]"); isbn = regex.Replace(isbn, string.Empty); if (isbn.Length >= 13) { isbn = isbn.Substring(0, 13); } else { isbn = isbn.Substring(0, 10); } ısbn_number.Text = isbn; } } } else { lblMessage.ForeColor = System.Drawing.Color.Red; lblMessage.Text = "Please select a file"; } }
private void ProcessGlobalKeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { if (e.Control && e.Shift && e.Alt) { switch (e.KeyCode) { // Shortcuts for changing bot settings. case Keys.F6: this.chkEnableConveienceKeys.IsChecked ^= true; break; // Shortcuts for setting the bounds of the region. case Keys.I: { System.Drawing.Point pt = System.Windows.Forms.Cursor.Position; SetTop(pt.Y); } break; case Keys.J: { System.Drawing.Point pt = System.Windows.Forms.Cursor.Position; SetLeft(pt.X); } break; case Keys.K: { System.Drawing.Point pt = System.Windows.Forms.Cursor.Position; SetRight(pt.X); } break; case Keys.M: { System.Drawing.Point pt = System.Windows.Forms.Cursor.Position; SetBottom(pt.Y); } break; // Shortcuts for defininig the top-left and bottom-right points of the region. case Keys.U: { System.Drawing.Point pt = System.Windows.Forms.Cursor.Position; SetLeft(pt.X); SetTop(pt.Y); } break; case Keys.Oemcomma: { System.Drawing.Point pt = System.Windows.Forms.Cursor.Position; SetRight(pt.X); SetBottom(pt.Y); } break; // Debugging shortcuts case Keys.L: { System.Drawing.Point pt = System.Windows.Forms.Cursor.Position; System.Drawing.Rectangle rect = new System.Drawing.Rectangle(pt.X, pt.Y, 1, 1); using (System.Drawing.Bitmap bmp = WindowWrapper.ScreenCapture(rect)) { using (Bitmap24 bmp24 = Bitmap24.FromImage(bmp)) { bmp24.Lock(); int[] px = bmp24.GetPixel(0, 0); double lum = Bitmap24.CalculateLuminance(px); Console.WriteLine("({0}, {1}) -> ({1}) -> {2}", pt.X, pt.Y, string.Join(", ", px), lum); } } } break; case Keys.O: { System.Drawing.Rectangle bounds = new System.Drawing.Rectangle( _left, _top, _right - _left + 1, _bottom - _top + 1 ); using (System.Drawing.Bitmap bmp = WindowWrapper.ScreenCapture(bounds)) { bmp.Save(@"tmp.bmp"); } } break; } } }
public bool IntersectsWith(System.Drawing.Rectangle rect) { throw null; }
public static System.Drawing.Rectangle Intersect(System.Drawing.Rectangle a, System.Drawing.Rectangle b) { throw null; }
public void Intersect(System.Drawing.Rectangle rect) { }
public static System.Drawing.Rectangle Inflate(System.Drawing.Rectangle rect, int x, int y) { throw null; }
public static void DrawButton(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, string buttonText, System.Drawing.Font font, TextFormatFlags flags, System.Drawing.Image image, System.Drawing.Rectangle imageBounds, bool focused, System.Windows.Forms.VisualStyles.PushButtonState state) { }
private System.Drawing.Bitmap CreateThumbnail(String name, System.Drawing.Color color, String labelText, int fontSize, String image, String overlay, int width, int height) { bool debug = false; System.Drawing.Size targetImageSize = new System.Drawing.Size(width - (_BUTTON_INNER_BORDER * 2), height - (_BUTTON_INNER_BORDER * 2)); String stringResolution = ""; //Create a Working Bitmap System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(targetImageSize.Width, targetImageSize.Height); System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap); //Required else creates Bold Fonts Bug.....q afinal apenas tinha a ver c o nivel de transparencia da imagem e nao do code, umas horas a procura deste bug improvável... graphics.Clear(color); #pragma warning disable if (debug) { stringResolution = bitmap.HorizontalResolution + "x" + bitmap.VerticalResolution; bitmap.Save(FrameworkUtils.OSSlash(GlobalFramework.Path["temp"] + name + "_1_new_" + stringResolution + ".png")); } ; #pragma warning restore //Render Image Over bitmap if (image != string.Empty) { if (File.Exists(image)) { try { System.Drawing.Image imageButton = new System.Drawing.Bitmap(image); //_log.Debug(string.Format("CreateThumbnail(): imageButton: {0}x{1} resize to targetImageSize: {2}x{3}", imageButton.Width, imageButton.Height, targetImageSize.Width, targetImageSize.Height)); #pragma warning disable if (debug) { stringResolution = imageButton.HorizontalResolution + "x" + imageButton.VerticalResolution; imageButton.Save(FrameworkUtils.OSSlash(GlobalFramework.Path["temp"] + name + "_2_image_" + stringResolution + ".png")); } ; #pragma warning restore imageButton = Utils.ResizeAndCrop(imageButton, targetImageSize); System.Drawing.Graphics.FromImage(bitmap).DrawImage(imageButton, 0, 0); #pragma warning disable if (debug) { stringResolution = bitmap.HorizontalResolution + "x" + bitmap.VerticalResolution; bitmap.Save(FrameworkUtils.OSSlash(GlobalFramework.Path["temp"] + name + "_3_image_resized_" + stringResolution + ".png")); } ; #pragma warning restore } catch (FileNotFoundException ex) { _log.Error(string.Format("CreateThumbnail(): [{0}]", ex.Message), ex); } } } //Render Overlay Over bitmap if (overlay != string.Empty) { if (File.Exists(overlay)) { try { System.Drawing.Image imageOverlay = new System.Drawing.Bitmap(overlay); //System.Drawing.Image imageOverlay = System.Drawing.Image.FromFile(overlay); #pragma warning disable if (debug) { stringResolution = imageOverlay.HorizontalResolution + "x" + imageOverlay.VerticalResolution; imageOverlay.Save(FrameworkUtils.OSSlash(GlobalFramework.Path["temp"] + name + "_4_overlay_" + stringResolution + ".png")); } ; #pragma warning restore imageOverlay = Utils.ResizeAndCrop(imageOverlay, targetImageSize); System.Drawing.Graphics.FromImage(bitmap).DrawImage(imageOverlay, 0, 0); #pragma warning disable if (debug) { stringResolution = bitmap.HorizontalResolution + "x" + bitmap.VerticalResolution; bitmap.Save(FrameworkUtils.OSSlash(GlobalFramework.Path["temp"] + name + "_5_resized_" + stringResolution + ".png")); } ; #pragma warning restore } catch (FileNotFoundException ex) { _log.Error(string.Format("CreateThumbnail(): [{0}]", ex.Message), ex); } } } //Render Text Over bitmap if (labelText != string.Empty) { System.Drawing.Rectangle transpRectangle = new System.Drawing.Rectangle(); transpRectangle.Width = targetImageSize.Width - (_BUTTON_TEXT_OVERLAY_INNER_MARGIN * 4); transpRectangle.Height = fontSize * 2; transpRectangle.X = _BUTTON_TEXT_OVERLAY_INNER_MARGIN * 2; transpRectangle.Y = targetImageSize.Height - transpRectangle.Height - (_BUTTON_TEXT_OVERLAY_INNER_MARGIN * 2); Utils.ImageTextOverlay(bitmap, labelText, transpRectangle, System.Drawing.Color.Black, "Arial", fontSize, _BUTTON_TEXT_ALPHA_OVERLAY); #pragma warning disable if (debug) { bitmap.Save(FrameworkUtils.OSSlash(GlobalFramework.Path["temp"] + @"touchbuttonImage6_" + stringResolution + "_textoverlay.png")); } #pragma warning restore } if (_useCachedImages && !File.Exists(_pathCache + name + ".png")) { try { bitmap.Save(_pathCache + name + ".png"); } catch (Exception ex) { _log.Error(ex.Message, ex); } } return(bitmap); }
public RECT(System.Drawing.Rectangle r) : this(r.Left, r.Top, r.Right, r.Bottom) { }
public static System.Drawing.Rectangle Union(System.Drawing.Rectangle a, System.Drawing.Rectangle b) { throw null; }
private void btnShrinkToFit_Click(object sender, RoutedEventArgs e) { // Create a Rectangle defining the region. System.Drawing.Rectangle bounds = new System.Drawing.Rectangle( _left - 1, _top - 1, _right - _left + 3, _bottom - _top + 3 ); // Get the width and height of the region. int width = bounds.Width; int height = bounds.Height; // Quit if the width and the height are too small. if (width < 20 || height < 20) { MessageBox.Show("The defined region is too small. Please update the region and try again.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } // Get a screenshot of the defined region to process. using (System.Drawing.Bitmap bmp = WindowWrapper.ScreenCapture(bounds)) { using (Bitmap24 bmp24 = Bitmap24.FromImage(bmp)) { // Lock the bits in the Bitmap24 to directly access the raw data. bmp24.Lock(); // Compute how much to shift the left coordinate by. int leftShift = -1; int leftDark = 0; for (int x = 0; x < width; ++x) { System.Drawing.Rectangle rect = new System.Drawing.Rectangle(x, (height / 2) - CHECK_AROUND, 1, CHECK_SIZE); int currDark = CountDark(bmp24, rect); if (leftDark == CHECK_SIZE && currDark == 0) { leftShift = x - 1; break; } leftDark = currDark; } // Compute how much to shift the right coordinate by. int rightShift = -1; int rightDark = 0; for (int x = width - 1; x >= 0; --x) { System.Drawing.Rectangle rect = new System.Drawing.Rectangle(x, (height / 2) - CHECK_AROUND, 1, CHECK_SIZE); int currDark = CountDark(bmp24, rect); if (rightDark == CHECK_SIZE && currDark == 0) { rightShift = width - x - 2; break; } rightDark = currDark; } // Compute how much to shift the top coordinate by. int topShift = -1; int topDark = 0; for (int y = 0; y < height; ++y) { System.Drawing.Rectangle rect = new System.Drawing.Rectangle((width / 2) - CHECK_AROUND, y, CHECK_SIZE, 1); int currDark = CountDark(bmp24, rect); if (topDark == CHECK_SIZE && currDark == 0) { topShift = y - 1; break; } topDark = currDark; } // Compute how much to shift the bottom coordinate by. int bottomShift = -1; int bottomDark = 0; for (int y = height - 1; y >= 0; --y) { System.Drawing.Rectangle rect = new System.Drawing.Rectangle((width / 2) - CHECK_AROUND, y, CHECK_SIZE, 1); int currDark = CountDark(bmp24, rect); if (bottomDark == CHECK_SIZE && currDark == 0) { bottomShift = height - y - 2; break; } bottomDark = currDark; } // Define a list containing the ones that were not found. List <string> notFound = new List <string>(); // Check if a valid left shift was found. if (leftShift > 0) { SetLeft(_left + leftShift); } else if (leftShift < 0) { notFound.Add("Left"); } // Check if a valid right shift was found. if (rightShift > 0) { SetRight(_right - rightShift); } else if (rightShift < 0) { notFound.Add("Right"); } // Check if a valid top shift was found. if (topShift > 0) { SetTop(_top + topShift); } else if (topShift < 0) { notFound.Add("Top"); } // Check if a valid bottom shift was found. if (bottomShift > 0) { SetBottom(_bottom - bottomShift); } else if (bottomShift < 0) { notFound.Add("Bottom"); } if (notFound.Count > 0) { string errorMessage = "Unable to auto-detect the bounds. Please make sure that the defined region completely contains the game window, and that the game is displaying a bright image, such as the main screen.\n\nThe following dimensions were not found:\n\n" + string.Join("\n", notFound) + "\n\n"; MessageBox.Show(errorMessage, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } } }
public void DrawToBitmap(System.Drawing.Bitmap bitmap, System.Drawing.Rectangle targetBounds) { }
/// <summary> /// Our present hook that will grab a copy of the backbuffer when requested. Note: this supports multi-sampling (anti-aliasing) /// </summary> /// <param name="swapChainPtr"></param> /// <param name="syncInterval"></param> /// <param name="flags"></param> /// <returns>The HRESULT of the original method</returns> int PresentHook(IntPtr swapChainPtr, int syncInterval, SlimDX.DXGI.PresentFlags flags) { if (swapChainPtr != _swapChainPointer) { _swapChain = SlimDX.DXGI.SwapChain.FromPointer(swapChainPtr); } SwapChain swapChain = _swapChain; //using (SlimDX.DXGI.SwapChain swapChain = SlimDX.DXGI.SwapChain.FromPointer(swapChainPtr)) { try { #region Screenshot Request if (this.Request != null) { try { this.DebugMessage("PresentHook: Request Start"); DateTime startTime = DateTime.Now; using (Texture2D texture = Texture2D.FromSwapChain <SlimDX.Direct3D10.Texture2D>(swapChain, 0)) { #region Determine region to capture System.Drawing.Rectangle regionToCapture = new System.Drawing.Rectangle(0, 0, texture.Description.Width, texture.Description.Height); if (this.Request.RegionToCapture.Width > 0) { regionToCapture = this.Request.RegionToCapture; } #endregion var theTexture = texture; // If texture is multisampled, then we can use ResolveSubresource to copy it into a non-multisampled texture Texture2D textureResolved = null; if (texture.Description.SampleDescription.Count > 1) { this.DebugMessage("PresentHook: resolving multi-sampled texture"); // texture is multi-sampled, lets resolve it down to single sample textureResolved = new Texture2D(texture.Device, new Texture2DDescription() { CpuAccessFlags = CpuAccessFlags.None, Format = texture.Description.Format, Height = texture.Description.Height, Usage = ResourceUsage.Default, Width = texture.Description.Width, ArraySize = 1, SampleDescription = new SlimDX.DXGI.SampleDescription(1, 0), // Ensure single sample BindFlags = BindFlags.None, MipLevels = 1, OptionFlags = texture.Description.OptionFlags }); // Resolve into textureResolved texture.Device.ResolveSubresource(texture, 0, textureResolved, 0, texture.Description.Format); // Make "theTexture" be the resolved texture theTexture = textureResolved; } // Create destination texture Texture2D textureDest = new Texture2D(texture.Device, new Texture2DDescription() { CpuAccessFlags = CpuAccessFlags.None, // CpuAccessFlags.Write | CpuAccessFlags.Read, Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm, // Supports BMP/PNG Height = regionToCapture.Height, Usage = ResourceUsage.Default, // ResourceUsage.Staging, Width = regionToCapture.Width, ArraySize = 1, //texture.Description.ArraySize, SampleDescription = new SlimDX.DXGI.SampleDescription(1, 0), // texture.Description.SampleDescription, BindFlags = BindFlags.None, MipLevels = 1, //texture.Description.MipLevels, OptionFlags = texture.Description.OptionFlags }); // Copy the subresource region, we are dealing with a flat 2D texture with no MipMapping, so 0 is the subresource index theTexture.Device.CopySubresourceRegion(theTexture, 0, new ResourceRegion() { Top = regionToCapture.Top, Bottom = regionToCapture.Bottom, Left = regionToCapture.Left, Right = regionToCapture.Right, Front = 0, Back = 1 // Must be 1 or only black will be copied }, textureDest, 0, 0, 0, 0); // Note: it would be possible to capture multiple frames and process them in a background thread // Copy to memory and send back to host process on a background thread so that we do not cause any delay in the rendering pipeline Guid requestId = this.Request.RequestId; // this.Request gets set to null, so copy the RequestId for use in the thread ThreadPool.QueueUserWorkItem(delegate { //FileStream fs = new FileStream(@"c:\temp\temp.bmp", FileMode.Create); //Texture2D.ToStream(testSubResourceCopy, ImageFileFormat.Bmp, fs); DateTime startCopyToSystemMemory = DateTime.Now; using (MemoryStream ms = new MemoryStream()) { Texture2D.ToStream(textureDest, ImageFileFormat.Bmp, ms); ms.Position = 0; this.DebugMessage("PresentHook: Copy to System Memory time: " + (DateTime.Now - startCopyToSystemMemory).ToString()); DateTime startSendResponse = DateTime.Now; SendResponse(ms, requestId); this.DebugMessage("PresentHook: Send response time: " + (DateTime.Now - startSendResponse).ToString()); } // Free the textureDest as we no longer need it. textureDest.Dispose(); textureDest = null; this.DebugMessage("PresentHook: Full Capture time: " + (DateTime.Now - startTime).ToString()); }); // Make sure we free up the resolved texture if it was created if (textureResolved != null) { textureResolved.Dispose(); textureResolved = null; } } this.DebugMessage("PresentHook: Copy BackBuffer time: " + (DateTime.Now - startTime).ToString()); this.DebugMessage("PresentHook: Request End"); } finally { // Prevent the request from being processed a second time this.Request = null; } } #endregion #region Example: Draw overlay (after screenshot so we don't capture overlay as well) if (this.ShowOverlay) { using (Texture2D texture = Texture2D.FromSwapChain <SlimDX.Direct3D10.Texture2D>(swapChain, 0)) { if (_lastFrame != null) { FontDescription fd = new SlimDX.Direct3D10.FontDescription() { Height = 16, FaceName = "Times New Roman", IsItalic = false, Width = 0, MipLevels = 1, CharacterSet = SlimDX.Direct3D10.FontCharacterSet.Default, Precision = SlimDX.Direct3D10.FontPrecision.Default, Quality = SlimDX.Direct3D10.FontQuality.Antialiased, PitchAndFamily = FontPitchAndFamily.Default | FontPitchAndFamily.DontCare }; using (Font font = new Font(texture.Device, fd)) { DrawText(font, new Vector2(100, 100), String.Format("{0}", DateTime.Now), new Color4(System.Drawing.Color.Red)); } } _lastFrame = DateTime.Now; } } #endregion } catch (Exception e) { // If there is an error we do not want to crash the hooked application, so swallow the exception this.DebugMessage("PresentHook: Exeception: " + e.GetType().FullName + ": " + e.Message); } // As always we need to call the original method, note that EasyHook has already repatched the original method // so calling it here will not cause an endless recursion to this function return(swapChain.Present(syncInterval, flags).Code); } }
public void Invalidate(System.Drawing.Rectangle rc) { }
private void Initialize3DEnvironment() { DisplayAdapter adapterInfo = graphicsSettings.DisplayAdapter; DisplayDevice deviceInfo = graphicsSettings.DisplayDevice; isWindowed = graphicsSettings.IsWindowed; // Prepare window for possible windowed/fullscreen change // AdjustWindowForChange(); // Set up the presentation parameters RefreshPresentParameters(); if (deviceInfo.Caps.PrimitiveMiscCaps.IsNullReference) { // Warn user about null ref device that can't render anything throw new ApplicationException("null reference device"); } CreateFlags createFlags = new CreateFlags(); switch (graphicsSettings.VertexProcessingType) { case VertexProcessingType.Software: createFlags = CreateFlags.SoftwareVertexProcessing; break; case VertexProcessingType.Mixed: createFlags = CreateFlags.MixedVertexProcessing; break; case VertexProcessingType.Hardware: createFlags = CreateFlags.HardwareVertexProcessing; break; case VertexProcessingType.PureHardware: createFlags = CreateFlags.HardwareVertexProcessing | CreateFlags.PureDevice; break; default: throw new ApplicationException("Unable to determine vertex processing method."); } // Create the device device = new Device(graphicsSettings.AdapterOrdinal, graphicsSettings.DisplayDevice.DeviceType, this.viewport, createFlags, this.presentParameters); if (device != null) { // Cache our local objects renderStates = device.RenderState; samplerStates = device.SamplerState; textureStates = device.TextureState; // When moving from fullscreen to windowed mode, it is important to // adjust the window size after recreating the device rather than // beforehand to ensure that you get the window size you want. For // example, when switching from 640x480 fullscreen to windowed with // a 1000x600 window on a 1024x768 desktop, it is impossible to set // the window size to 1000x600 until after the display mode has // changed to 1024x768, because windows cannot be larger than the // desktop. if (graphicsSettings.IsWindowed && (this.viewport is System.Windows.Forms.Form)) { // Make sure main window isn't topmost, so error message is visible this.viewport.Location = new System.Drawing.Point(rectWindowBounds.Left, rectWindowBounds.Top); this.viewport.Size = new System.Drawing.Size((rectWindowBounds.Right - rectWindowBounds.Left), (rectWindowBounds.Bottom - rectWindowBounds.Top)); } // Store device Caps graphicsCaps = device.DeviceCaps; behavior = createFlags; // Store render target surface desc Surface BackBuffer = device.GetBackBuffer(0, 0, BackBufferType.Mono); backBufferDesc = BackBuffer.Description; BackBuffer.Dispose(); BackBuffer = null; // Set up the fullscreen cursor if (showFullScreenCursor && !graphicsSettings.IsWindowed) { System.Windows.Forms.Cursor ourCursor = this.viewport.Cursor; device.SetCursor(ourCursor, true); device.ShowCursor(true); } // Confine cursor to fullscreen window if (clipFullScreenCursor) { if (!isWindowed) { System.Drawing.Rectangle rcWindow = this.viewport.ClientRectangle; } } // Setup the event handlers for our device device.DeviceLost += InvalidateDeviceObjects; device.DeviceReset += RestoreDeviceObjects; device.Disposing += DeleteDeviceObjects; device.DeviceResizing += new CancelEventHandler(EnvironmentResized); // Initialize the app's device-dependent objects try { if (InitDeviceObjects != null) { InitDeviceObjects(null, null); } if (RestoreDeviceObjects != null) { RestoreDeviceObjects(null, null); } return; } catch { // Cleanup before we try again if (InvalidateDeviceObjects != null) { InvalidateDeviceObjects(null, null); } if (DeleteDeviceObjects != null) { DeleteDeviceObjects(null, null); } device.Dispose(); device = null; if (this.viewport.Disposing) { return; } } } // HACK: removed fallback to reference rasterizer /* * // If that failed, fall back to the reference rasterizer * if( deviceInfo.DevType == Direct3D.DeviceType.Hardware ) * { * if (FindBestWindowedMode(false, true)) * { * isWindowed = true; * if(viewport is System.Windows.Forms.Form) * { * // Make sure main window isn't topmost, so error message is visible * this.viewport.Location = new System.Drawing.Point(windowBoundsRect.Left, windowBoundsRect.Top); * this.viewport.Size = new System.Drawing.Size(( windowBoundsRect.Right - windowBoundsRect.Left ), ( windowBoundsRect.Bottom - windowBoundsRect.Top)); * //AdjustWindowForChange(); * } * * // Let the user know we are switching from HAL to the reference rasterizer * //DisplayErrorMsg( null, AppMsgType.WarnSwitchToRef); * * Initialize3DEnvironment(); * } * } */ }
public void Invalidate(System.Drawing.Rectangle rc, bool invalidateChildren) { }
public void PaintValue(object value, System.Drawing.Graphics canvas, System.Drawing.Rectangle rectangle) { }
public System.Drawing.Rectangle RectangleToClient(System.Drawing.Rectangle r) { }
public static extern int GetWindowRect(int int_0, ref System.Drawing.Rectangle rectangle_0);
public System.Drawing.Rectangle RectangleToScreen(System.Drawing.Rectangle r) { }
public static void DrawButton(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, System.Drawing.Image image, System.Drawing.Rectangle imageBounds, bool focused, System.Windows.Forms.VisualStyles.PushButtonState state) { }
public void Draw(Graphics g, Rectangle r, ShadowSide sides) { if (!IsValidRectToDrawShadow(r)) { throw new ArgumentException("Rect is too small", "r"); } r.Inflate(-2, -2); if ((sides & ShadowSide.Middle) != 0) { g.FillRectangle(inner, r); } if ((sides & ShadowSide.Top) != 0) { g.FillRectangle(border1, r.Left, r.Top - 1, r.Width, 1); g.FillRectangle(border2, r.Left, r.Top - 2, r.Width, 1); } if ((sides & ShadowSide.Right) != 0) { g.FillRectangle(border1, r.Right, r.Top, 1, r.Height); g.FillRectangle(border2, r.Right + 1, r.Top, 1, r.Height); } if ((sides & ShadowSide.Bottom) != 0) { g.FillRectangle(border1, r.Left, r.Bottom, r.Width, 1); g.FillRectangle(border2, r.Left, r.Bottom + 1, r.Width, 1); } if ((sides & ShadowSide.Left) != 0) { g.FillRectangle(border1, r.Left - 1, r.Top, 1, r.Height); g.FillRectangle(border2, r.Left - 2, r.Top, 1, r.Height); } if ((sides & ShadowSide.Left) != 0 && (sides & ShadowSide.Top) != 0) { g.FillRectangle(edge1, r.Left - 1, r.Top - 1, 1, 1); g.FillRectangle(edge2, r.Left - 2, r.Top - 1, 1, 1); g.FillRectangle(edge2, r.Left - 1, r.Top - 2, 1, 1); g.FillRectangle(edge3, r.Left - 2, r.Top - 2, 1, 1); } if ((sides & ShadowSide.Top) != 0 && (sides & ShadowSide.Right) != 0) { g.FillRectangle(edge1, r.Right, r.Top - 1, 1, 1); g.FillRectangle(edge2, r.Right, r.Top - 2, 1, 1); g.FillRectangle(edge2, r.Right + 1, r.Top - 1, 1, 1); g.FillRectangle(edge3, r.Right + 1, r.Top - 2, 1, 1); } if ((sides & ShadowSide.Right) != 0 && (sides & ShadowSide.Bottom) != 0) { g.FillRectangle(edge1, r.Right, r.Bottom, 1, 1); g.FillRectangle(edge2, r.Right + 1, r.Bottom, 1, 1); g.FillRectangle(edge2, r.Right, r.Bottom + 1, 1, 1); g.FillRectangle(edge3, r.Right + 1, r.Bottom + 1, 1, 1); } if ((sides & ShadowSide.Bottom) != 0 && (sides & ShadowSide.Left) != 0) { g.FillRectangle(edge1, r.Left - 1, r.Bottom, 1, 1); g.FillRectangle(edge2, r.Left - 1, r.Bottom + 1, 1, 1); g.FillRectangle(edge2, r.Left - 2, r.Bottom, 1, 1); g.FillRectangle(edge3, r.Left - 2, r.Bottom + 1, 1, 1); } }
/// <summary> /// Converts the <see cref="System.Drawing.Rectangle"/> to the <see cref="Accord.Extensions.Rectangle"/>. /// </summary> /// <param name="rect"><see cref="System.Drawing.Rectangle"/></param> /// <returns><see cref="Accord.Extensions.Rectangle"/></returns> public static Rectangle ToRect(this System.Drawing.Rectangle rect) { return(new Rectangle(rect.X, rect.Y, rect.Width, rect.Height)); }
public static bool IsValidRectToDrawShadow(Rectangle r) { return(r.Width >= MinimumRectSize.Width && r.Height >= MinimumRectSize.Height); }
public bool Contains(System.Drawing.Rectangle rect) { throw null; }
public static void DrawParentBackground(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, Control childControl) { }