CreateGraphics() public method

public CreateGraphics ( ) : Graphics
return System.Drawing.Graphics
Example #1
1
 public VisibleSurface(Control surface)
     : base(surface.Width, surface.Height)
 {
     base.DC = surface.CreateGraphics();
     base.Buffer = new Backbuffer(this);
     this.RedrawDirtyRectangleOnly = true;
 }
Example #2
0
        internal static float GetCurrentScaling(this sys.Control control)
        {
            var   graphics      = control.CreateGraphics();
            float scalingFactor = graphics.DpiY / 96; //96 DPI corresponds to 100% scaling

            return(scalingFactor);
        }
Example #3
0
    public static Image GetImage(Control c_)
    {
      Graphics g = null;
      Image ret = null;
      try
      {
        if (c_ is Form)
          c_.BringToFront();
        else
          c_.FindForm().BringToFront();

        Application.DoEvents();

        g = c_.CreateGraphics();
        ret = new Bitmap(c_.ClientRectangle.Width, c_.ClientRectangle.Height, g);
        Graphics g2 = Graphics.FromImage(ret);
        IntPtr dc1 = g.GetHdc();
        IntPtr dc2 = g2.GetHdc();
        BitBlt(dc2, 0, 0, c_.ClientRectangle.Width, c_.ClientRectangle.Height, dc1, 0, 0, 13369376);
        g.ReleaseHdc(dc1);
        g2.ReleaseHdc(dc2);
      }
      finally
      {
        if (g != null)
          g.Dispose();
      }

      return ret;
    }
Example #4
0
 public static string GetCompactPath(this FileSystemInfo info, int newWidth, Font drawFont)
 {
     using (Control ctrl = new Control())
        {
     Graphics g = ctrl.CreateGraphics();
     string longPath = info.FullName;
     int width = g.MeasureString(longPath, drawFont).ToSize().Width;
     if (width <= newWidth)
      return longPath;
     int aveCharWidth = width / longPath.Length;
     int charCount = newWidth / aveCharWidth;
     StringBuilder builder = new StringBuilder();
     builder.Append(longPath);
     builder.EnsureCapacity(charCount);
     while (g.MeasureString(builder.ToString(), drawFont).Width > newWidth)
     {
      if (!NativeMethods.PathCompactPathEx(builder, longPath,
       (uint)charCount--, 0))
      {
       return string.Empty;
      }
     }
     return builder.ToString();
        }
 }
Example #5
0
            public static Image GetControlScreenshot(System.Windows.Forms.Control control)
            {
                object x      = new object();
                Bitmap bitmap = null;

                lock (control)
                {
                    if (control == null || control.Handle == IntPtr.Zero)
                    {
                        return((Image)bitmap);
                    }

                    if (control.Width < 1 || control.Height < 1)
                    {
                        return((Image)bitmap);
                    }

                    if (bitmap != null)
                    {
                        bitmap.Dispose();
                    }

                    // preparing the bitmap.
                    bitmap = new Bitmap(control.Width, control.Height);

                    bitmap = GetImage(control.CreateGraphics(), control.Width, control.Height, 0);
                }

                return((Image)bitmap);
            }
Example #6
0
        /// <summary>
        /// Execute the capturing of a specified rectangle in a given window.
        /// </summary>
        /// <param name="window">The window to capture</param>
        /// <param name="rc">The rectangle used for capturing</param>
        /// <returns>The image which has been captured.</returns>
        private Bitmap capture(System.Windows.Forms.Control window, Rectangle rc)
        {
            Bitmap memoryImage = null;

            images = new Bitmap[1];

            try
            {
                // Create new graphics object using handle to window.
                using (Graphics graphics = window.CreateGraphics())
                {
                    memoryImage = new Bitmap(rc.Width, rc.Height, graphics);

                    using (Graphics memoryGrahics = Graphics.FromImage(memoryImage))
                    {
                        memoryGrahics.CopyFromScreen(rc.X, rc.Y, 0, 0, rc.Size, CopyPixelOperation.SourceCopy);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Capture failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            images[0] = memoryImage;
            return(memoryImage);
        }
Example #7
0
 public void XmlSerialize(XmlWriter writer, Control detailView)
 {
     writer.WriteStartElement("DetailView");
     int dpiX = 0x60;
     int dpiY = 0x60;
     if (true)
     {
         Graphics graphics = detailView.CreateGraphics();
         dpiX = (int) graphics.DpiX;
         dpiY = (int) graphics.DpiY;
         graphics.Dispose();
         graphics = null;
     }
     writer.WriteAttributeString("DpiX", Convert.ToString(dpiX));
     writer.WriteAttributeString("DpiY", Convert.ToString(dpiY));
     this.SerializeDetailViewProperties(writer, detailView);
     IList propertyValue = (IList) ReflectionHelper.GetPropertyValue(detailView, "Items");
     foreach (object obj2 in propertyValue)
     {
         writer.WriteStartElement("Item");
         Type type = obj2.GetType();
         if (type.Assembly.ManifestModule.Name.ToLower().StartsWith("resco.detailview"))
         {
             writer.WriteAttributeString("Type", type.FullName);
         }
         else
         {
             writer.WriteAttributeString("Type", type.AssemblyQualifiedName);
         }
         this.SerializeProperties(writer, obj2);
         writer.WriteEndElement();
     }
 }
Example #8
0
 /// <summary>
 /// Returns relation between current graphics resolution and default DpiY (96.0).
 /// Can be used when arranging controls and resizing forms.
 /// </summary>
 /// <param name="control"></param>
 /// <returns></returns>
 public static float CalculateGraphicsProportion(Control control)
 {
     Graphics graphics = control.CreateGraphics();
     float proportion = (float)(graphics.DpiY / 96.0);
     graphics.Dispose();
     return proportion;
 }
Example #9
0
        /// <summary>
        /// Returns true if any part of the client based rectangle is visible.
        /// </summary>
        /// <param name="control">Control to check.</param>
        /// <param name="rectangleToCheck">Client based rectangle to check.</param>
        public static bool IsClientRectangleVisible( Control control, Rectangle rectangleToCheck )
        {
            if( !control.IsHandleCreated )
            {
                return false;
            }

            Utility.Win32.Common.RECT rcClip, rcClient = new Utility.Win32.Common.RECT( rectangleToCheck );

            using( Graphics grfx = control.CreateGraphics() )
            {
                IntPtr hdc = IntPtr.Zero;

                try
                {
                    hdc = grfx.GetHdc();

                    RegionValue result = (RegionValue) Gdi.GetClipBox( hdc, out rcClip );

                    return result != RegionValue.NULLREGION;
                }
                finally
                {
                    if( hdc != IntPtr.Zero )
                    {
                        grfx.ReleaseHdc( hdc );
                    }
                }
            }
        }
Example #10
0
        internal static sys.Control ForceAutoScale(this sys.Control control)
        {
            var   graphics      = control.CreateGraphics();
            float scalingFactor = graphics.DpiY / 96; //96 DPI corresponds to 100% scaling

            control.Scale(new SizeF(scalingFactor, scalingFactor));
            return(control);
        }
 /// <summary>
 /// This method provides the width of a given text, with the given font
 /// 
 /// </summary>
 /// <param name="text"></param>
 /// <param name="size"></param>
 /// <returns>Text width</returns>
 protected int GetTextWidth(string text, Control control)
 {
     float textwidth=0;
     Graphics g = control.CreateGraphics();
     textwidth = (int)g.MeasureString(text, control.Font).Width;
     g.Dispose();
     return (int)Math.Ceiling(textwidth);
 }
        public void GenerateBackground(Control control)
        {
            Graphics g = control.CreateGraphics();
            Size size = control.ClientSize;

            GenerateBackground(g, size);

            g.Dispose();
        }
Example #13
0
        public TextGeometry(Control control)
        {
            this.control = control;
            g = control.CreateGraphics();
            stringFormat.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces;

            charWidth = MeasureString("_");
            lineHeight = Font.Height;
        }
 public TileManager(System.Windows.Forms.Control control)
 {
     parent = control;
     using (Graphics g = parent.CreateGraphics())
     {
         dpiX = g.DpiX;
         dpiY = g.DpiY;
     }
 }
Example #15
0
 public VisibleSurface(Control surface, GridPointMatrixes drawSource)
     : base(surface.Width, surface.Height)
 {
     base.DC = surface.CreateGraphics();
     base.Buffer = new Backbuffer(this)
         {
             DrawSource = drawSource
         };
     this.RedrawDirtyRectangleOnly = true;
 }
        /// <summary>
        /// Instantiates a new <see cref="Graphics"/> object with the specified
        /// <paramref name="control"/>.
        /// </summary>
        /// <param name="control">The desired value of
        /// <see cref="Control"/>.</param>
        /// <exception cref="ArgumentNullException"><paramref name="control"/>
        /// is <c>null</c>.</exception>
        public Graphics(Control control)
        {
            if (ReferenceEquals(control, null))
            {
                throw new ArgumentNullException(nameof(control));
            }

            Control = control;
            native = Control.CreateGraphics();
        }
Example #17
0
 private static void LoadDeviceScaling()
 {
     using (var control = new Control())
     {
         using (var graphics = control.CreateGraphics())
         {
             _deviceScaleX = 96.0 / graphics.DpiX;
             _deviceScaleY = 96.0 / graphics.DpiY;
         }
     }
 }
Example #18
0
        public ObjectNet(string name, ObjectSequence inObj, ObjectSequence outObj, Control _ControlHandle)
        {
            netName = name;
            inputObject = inObj;
            inputObject.UpdatePosition += new ObjectSequence.ObjectPosistionMove(inputObject_UpdatePosition);

            outputObject = outObj;
            outputObject.UpdatePosition += new ObjectSequence.ObjectPosistionMove(outputObject_UpdatePosition);

            canvas = _ControlHandle.CreateGraphics();
        }
Example #19
0
        private int TextWidth(Control c, string s)
        {
            double   factor = 1.15;
            Graphics g      = c.CreateGraphics();

            System.Drawing.Font font = c.Font;

            int newWidth;

            newWidth = (int)Math.Round(g.MeasureString(s.ToUpper(), font).Width *factor) + 20;
            return(newWidth);
        }
 public AnimateGradient(Control control, Color color1, Color color2, float gradientAngle, Control label)
 {
     _timer.Interval = 100;
     _timer.Tick += _timer_Tick;
     _control = control;
     _clientRectangle = control.ClientRectangle;
     _graphics = control.CreateGraphics();
     _angle = gradientAngle;
     _color1 = color1;
     _color2 = color2;
     _label = label;
 }
Example #21
0
		// Token: 0x060025F9 RID: 9721
		// RVA: 0x000E3B88 File Offset: 0x000E1D88
		internal static float smethod_0(Control control_0, bool bool_0)
		{
			if (!bool_0 && Class611.float_0 > 0f)
			{
				return Class611.float_0;
			}
			float result;
			using (Graphics graphics = control_0.CreateGraphics())
			{
				result = (Class611.float_0 = graphics.DpiX);
			}
			return result;
		}
Example #22
0
 public Bitmap CaptureScreen(Control con, int fromX, int fromY)
 {
     Size size = con.Size;
     Graphics g = con.CreateGraphics();
     Bitmap image = new Bitmap(size.Width - fromX, size.Height - fromY, g);
     Graphics graphics2 = Graphics.FromImage(image);
     IntPtr hdc = g.GetHdc();
     IntPtr hdcDest = graphics2.GetHdc();
     BitBlt(hdcDest, 0, 0, con.ClientRectangle.Width - fromX, con.ClientRectangle.Height - fromY, hdc, fromX, fromY, 0xcc0020);
     g.ReleaseHdc(hdc);
     graphics2.ReleaseHdc(hdcDest);
     return image;
 }
Example #23
0
 private void centerString(Control label)
 {
     Graphics g = label.CreateGraphics();
        try
        {
     SizeF size = g.MeasureString(label.Text, label.Font);
     label.Width = (int)Math.Ceiling(size.Width);
     label.Left = (ClientRectangle.Width - (int)size.Width) / 2;
        }
        finally
        {
     g.Dispose();
        }
 }
        /// <summary>
        /// Paints a TRUE transparent background to the control
        /// </summary>
        /// <param name="control"></param>
        /// <param name="e"></param>
        static public void PaintTransparentBackground(this Control control, PaintEventArgs e)
        {
            if (control == null)
            {
                throw new ArgumentNullException(nameof(control));
            }

            if (e == null)
            {
                e = new PaintEventArgs(control.CreateGraphics(), control.ClientRectangle);
            }

            BorderStyle borderStyle = BorderStyle.None;

            try
            {
                borderStyle = control.GetValueOf <BorderStyle>("BorderStyle");
            }
            catch (Exception)
            {
                borderStyle = BorderStyle.None;
            }

            Graphics g = e.Graphics;

            foreach (Control item in control.IntersectsControlsDown())
            {
                // Check it's visible and overlaps this control
                if (item.Bounds.IntersectsWith(control.Bounds) && item.Visible)
                {
                    // Load appearance of underlying control and redraw it on this background
                    Bitmap bmp = new Bitmap(item.Width, item.Height, g);
                    item.DrawToBitmap(bmp, item.ClientRectangle);
                    switch (borderStyle)
                    {
                    /*
                     * SystemInformation.BorderSize
                     * SystemInformation.Border3DSize
                     */

                    default:     //BorderStyle.None
                        g.TranslateTransform(item.Left - control.Left, item.Top - control.Top);
                        break;
                    }
                    g.DrawImageUnscaled(bmp, System.Drawing.Point.Empty);
                    g.TranslateTransform(control.Left - item.Left, control.Top - item.Top);
                    bmp.Dispose();
                }
            }
        }
Example #25
0
 /// <summary>
 /// Gets the graphics object from the given control
 /// </summary>
 /// <param name="control">Control to obtain the graphics from</param>
 /// <returns>A graphics object with the control's characteristics</returns>
 public System.Drawing.Graphics GetGraphics(System.Windows.Forms.Control control)
 {
     System.Drawing.Graphics graphic;
     if (control.Visible == true)
     {
         graphic = control.CreateGraphics();
         SetColor(graphic, control.ForeColor);
         SetFont(graphic, control.Font);
     }
     else
     {
         graphic = null;
     }
     return(graphic);
 }
		public static int GetTextBaseline(Control ctrl, ContentAlignment alignment)
		{
			if (ctrl == null)
			{
				throw new ArgumentNullException("ctrl");
			}

			Rectangle ctrlRect = ctrl.ClientRectangle;
			
			int ascent = 0;
			int height = 0;
			
			using (Graphics grfx = ctrl.CreateGraphics())
			{
				IntPtr hDC = grfx.GetHdc();
				IntPtr hFont = ctrl.Font.ToHfont();
				
				try
				{
					IntPtr oldFont = Gdi32.SelectObject(hDC, hFont);
					TEXTMETRIC textMetric = new TEXTMETRIC();

					Gdi32.GetTextMetrics(hDC, textMetric);
					
					ascent = textMetric.tmAscent + 1;
					height = textMetric.tmHeight;
					
					Gdi32.SelectObject(hDC, oldFont);
				}
				finally
				{
					Gdi32.DeleteObject(hFont);
					grfx.ReleaseHdc(hDC);
				}
			}
			
			if ((alignment & NuGenControlPaint.AnyTop) != 0)
			{
				return (ctrlRect.Top + ascent);
			}
			
			if ((alignment & NuGenControlPaint.AnyMiddle) != 0)
			{
				return (((ctrlRect.Top + (ctrlRect.Height / 2)) - (height / 2)) + ascent);
			}
			
			return ((ctrlRect.Bottom - height) + ascent);
		}
Example #27
0
		public Win32FontSystem( Control control )
		{
			// Get the list of font families.
			LOGFONT lf = CreateLogFont();

			IntPtr plogFont = Marshal.AllocHGlobal( Marshal.SizeOf( lf ) );
			Marshal.StructureToPtr( lf, plogFont, true );

			using ( Graphics g = control.CreateGraphics() )
			{
				try
				{
					IntPtr hDC = g.GetHdc();

					EnumFontExDelegate callback = 
						delegate( ref ENUMLOGFONTEX lpelfe, ref NEWTEXTMETRICEX lpntme, int FontType, int lParam )
						{
							try
							{
								// For now, just get the western font names..
								if ( lpelfe.elfScript == "Western" )
								{
									_familyLogFonts[ lpelfe.elfFullName ] = lpelfe.elfLogFont;
								}
							}
							catch ( Exception e )
							{
								System.Diagnostics.Trace.WriteLine(e.ToString());
							}
							return 1;
						};

					EnumFontFamiliesEx( hDC, plogFont, callback, IntPtr.Zero, 0 );
					_familyNames = _familyLogFonts.Keys.ToList();

					g.ReleaseHdc( hDC );
				}
				catch
				{
					MessageBox.Show( "Error enumerating Win32 fonts" );
					Debug.Assert( false );
				}
				finally
				{
					Marshal.DestroyStructure( plogFont, typeof( LOGFONT ) );
				}
			}
		}
Example #28
0
		/// <summary>
		/// Gets the average character size in the font associated to the specified control.
		/// Works only for fixed-pitch fonts.
		/// </summary>
		public static Size  GetFixedCharacterSize ( Control  window )
		   {
			String				test		=  new String ( '0', 80 ) ;
			System. Drawing. Graphics	gdi		=  window. CreateGraphics ( ) ;
			SizeF				fsize ;
			Size				size		=  new Size ( ) ;

			gdi. PageUnit		=  GraphicsUnit. Pixel ;
			fsize			=  gdi. MeasureString ( test, window. Font ) ;
			gdi. Dispose ( ) ;

			size. Width	=  ( int ) ( fsize. Width / 80 ) ;
			size. Height	=  ( int ) fsize. Height ;

			return ( size ) ;
		    }
Example #29
0
        public MouseEventListener(Control control)
        {
            Form = control;
            gfx = Form.CreateGraphics();
            DrawCross(Drawing.Color.LightGray, new Drawing.Point(Form.ClientRectangle.Width / 2, Form.ClientRectangle.Height / 2));
            string myIP = "127.0.0.1";
            //myIP = "192.168.1.141"; //e1
            //myIP = "192.168.1.136"; //e2
            //myIP = "192.168.1.108"; //diplom-vm bei wkm

            //put a bounding box around all the points for drawing in a
            //different size

            controller = new ClientCommunication(this, myIP); //xxx todo: this is not correct. the view is desktopApp.Winformgui, not inputarea
            OnlyActiveStrokeFinished = controller.SendPointList;
        }
Example #30
0
		public static void DrawControlToBitMap(Control srcControl, Bitmap destBitmap, Rectangle destBounds)
		{
			
			using (var srcGraph = srcControl.CreateGraphics())
			{
				var srcHdc = srcGraph.GetHdc();
				User32.SendMessage(srcControl.Handle, User32.WM.WM_PRINT, (int) srcHdc, 30);
				using (var destGraph = Graphics.FromImage(destBitmap))
				{
					var destHdc = destGraph.GetHdc();
					BitBlt(destHdc, destBounds.X, destBounds.Y, destBounds.Width, destBounds.Height,
					       srcHdc, 0, 0, TernaryRasterOperations.SRCCOPY);
					destGraph.ReleaseHdc(destHdc);
				}
				srcGraph.ReleaseHdc(srcHdc);
			}
		}
Example #31
0
 /// <summary>
 /// Verilen Control Nesnesinin resmini bitmap olarak döndürür.
 /// .NET 4.0 da System.Drawing ve System.Windows.Forms
 /// kütüphanelerinin eklenmesi gerekir.
 /// </summary>
 /// <param name="control">Control nesnesi</param>
 /// <returns>Verilen Control Nesnesinin resmini bitmap olarak döndürür.</returns>
 public System.Drawing.Bitmap ControlResmi(System.Windows.Forms.Control control)
 {
     System.Drawing.Bitmap controlBmp;
     using (System.Drawing.Graphics g1 = control.CreateGraphics())
     {
         controlBmp = new System.Drawing.Bitmap(control.Width, control.Height, g1);
         using (System.Drawing.Graphics g2 = System.Drawing.Graphics.FromImage(controlBmp))
         {
             System.IntPtr dc1 = g1.GetHdc();
             System.IntPtr dc2 = g2.GetHdc();
             BitBlt(dc2, 0, 0, control.Width, control.Height, dc1, 0, 0, 13369376);
             g1.ReleaseHdc(dc1);
             g2.ReleaseHdc(dc2);
         }
     }
     return(controlBmp);
 }
        private static void InitScaleFactors(Control c)
        {
            if (c == null)
            {
                xScale = 1.0f;
                yScale = 1.0f;
            }
            else
            {
                using (Graphics g = c.CreateGraphics())
                {
                    xScale = g.DpiX / 96.0f;
                    yScale = g.DpiY / 96.0f;
                }
            }

            initScales = true;
        }
Example #33
0
        public static Bitmap CaptureControl(Control control)
        {
            Bitmap controlBmp;
            using (Graphics g1 = control.CreateGraphics())
            {
                controlBmp = new Bitmap(control.Width, control.Height, g1);
                using (Graphics g2 = Graphics.FromImage(controlBmp))
                {
                    IntPtr dc1 = g1.GetHdc();
                    IntPtr dc2 = g2.GetHdc();
                    BitBlt(dc2, 0, 0, control.Width, control.Height, dc1, 0, 0, 13369376);
                    g1.ReleaseHdc(dc1);
                    g2.ReleaseHdc(dc2);
                }
            }

            return controlBmp;
        }
Example #34
0
 public virtual void Drawing_Gates(Control panel1)
 {
     int X, Y;
     X = GateContainer.ContainerScreenLocation.X + 40;
     Y = GateContainer.ContainerScreenLocation.Y + 10;
     Pen pen = new Pen(Color.Black, 1);
     SolidBrush sb = new SolidBrush(Color.Black);
     Graphics g = panel1.CreateGraphics();
     g.DrawPie(pen, X - (width / 2), Y, width, height, 270, 180); //curve
     g.DrawLine(pen, new Point(X, Y + 5), new Point(X - 30, Y + 5));// first horizontal line
     g.DrawLine(pen, new Point(X, Y + width - 5), new Point(X - 30, Y + width - 5));// Second Horizontal line
     g.DrawLine(pen, new Point(X + (width / 2), Y + (height / 2)), new Point(X + (width / 2) + 30, Y + (height / 2)));// last horizontal line
     Rectangle inputRect1 = new Rectangle(X - 30 - RectWidthAndHeight, Y + RectWidthAndHeight / 2, RectWidthAndHeight, RectWidthAndHeight);// initialize first rectangle
     Rectangle inputRect2 = new Rectangle(X - 30 - RectWidthAndHeight, Y + RectWidthAndHeight + height - 12, RectWidthAndHeight, RectWidthAndHeight);//initialize secind rectangle
     Rectangle outputRect = new Rectangle(X + width / 2 + 30 - RectWidthAndHeight + 5, Y + height / 2 - RectWidthAndHeight + 3, RectWidthAndHeight, RectWidthAndHeight);
     g.FillRectangle(sb, inputRect1); // first rectangle
     g.FillRectangle(sb, inputRect2);// second rectangle
     g.FillRectangle(sb, outputRect);//output rectangle
 }
Example #35
0
        /// <summary>
        /// parse the values for the character
        /// </summary>
        public void Parse(Control refCtrl,FontDefinition fd,Font font,char c,bool doCompression)
        {
            SizeF size;

              this.Character=c;

              // space is a special case

              if(c==' ') {
            ParseSpace(refCtrl,font);
            return;
              }

              using(Graphics g=refCtrl.CreateGraphics()) {

            g.TextRenderingHint=fd.Hint;

            // get the size that the system thinks the character occupies

            size=TextRenderer.MeasureText(g,c.ToString(),font,new Size(int.MaxValue,int.MaxValue),TextFormatFlags.NoPadding | TextFormatFlags.NoPrefix);

            this.CharacterBitmap=new Bitmap(Convert.ToInt32(size.Width)+fd.ExtraSpacing.Width,Convert.ToInt32(font.GetHeight())+fd.ExtraSpacing.Height);
            this.Size=this.CharacterBitmap.Size;

            using(Graphics charGraphics=Graphics.FromImage(this.CharacterBitmap)) {

              charGraphics.TextRenderingHint=fd.Hint;

              using(SolidBrush backBrush=new SolidBrush(fd.Background))
            charGraphics.FillRectangle(backBrush,0,0,this.CharacterBitmap.Width,this.CharacterBitmap.Height);

              // draw the character into the center of the bitmap

              TextRenderer.DrawText(charGraphics,c.ToString(),font,new Point(0,0),fd.Foreground,fd.Background,TextFormatFlags.NoPadding | TextFormatFlags.NoPrefix);
            }

            // scan the bitmap

            if(doCompression)
              ScanBitmap(this.CharacterBitmap,fd);
              }
        }
Example #36
0
        /*
           * get the character bitmap
           */
        public static bool[,] GetCharacterBitmap(Control refControl_,Font f_,char c_,int xoffset_,int yoffset_,int extraLines_)
        {
            bool[,] values;
              int x,y,width;
              Bitmap bm;
              Color cr;

              using(Graphics g=refControl_.CreateGraphics())
              {
            g.TextRenderingHint=TextRenderingHint.SingleBitPerPixel;

            if(c_==' ')
              width=(int)g.MeasureString("-",f_,PointF.Empty,StringFormat.GenericTypographic).Width;
            else
              width=(int)g.MeasureString(c_.ToString(),f_,PointF.Empty,StringFormat.GenericTypographic).Width;

            bm=new Bitmap(width,(int)f_.Size+extraLines_,g);

            using(Graphics g2=Graphics.FromImage(bm))
            {
              g2.FillRectangle(Brushes.White,0,0,bm.Width,bm.Height);

              g2.TextRenderingHint=TextRenderingHint.SingleBitPerPixel;
              g2.DrawString(c_.ToString(),f_,Brushes.Black,xoffset_,yoffset_,StringFormat.GenericTypographic);

              values=new bool[bm.Width,bm.Height];

              for(y=0;y<bm.Height;y++)
              {
            for(x=0;x<bm.Width;x++)
            {
              cr=bm.GetPixel(x,y);

              values[x,y]=cr.B==0 && cr.G==0 && cr.R==0;
            }
              }
            }
              }

              return values;
        }
Example #37
0
 public System.Drawing.Graphics GetGraphics(System.Windows.Forms.Control control)
 {
     System.Drawing.Graphics graphic;
     if (control.Visible == true)
     {
         graphic = control.CreateGraphics();
         if (this[graphic] == null)
         {
             GraphicsProperties tempProps = new GraphicsProperties();
             tempProps.color       = control.ForeColor;
             tempProps.BackColor   = control.BackColor;
             tempProps.TextColor   = control.ForeColor;
             tempProps.GraphicFont = control.Font;
             Add(graphic, tempProps);
         }
     }
     else
     {
         graphic = null;
     }
     return(graphic);
 }
Example #38
0
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            Control p = this.Parent;

            if (p != null)
            {
                Graphics g = p.CreateGraphics();
                if (this.BorderColor != Color.Empty)
                {
                    using (Pen borderPen = new Pen(this.BorderColor, _borderSize))
                    {
                        g.DrawRectangle(borderPen, new Rectangle(
                                            this.Bounds.X - _borderSize,
                                            this.Bounds.Y - _borderSize,
                                            this.Bounds.Width + _borderSize * 2,
                                            this.Bounds.Height + _borderSize * 2));
                    }

                    //p.Invalidate();
                }
            }
        }
Example #39
0
        public static string GetRTFFromTgaFile(string strFileName, Control CurControl, int nFrame)
        {
            int nIndexPos = strFileName.LastIndexOf(".");
            string ExpandName = strFileName.Substring(nIndexPos, strFileName.Length - nIndexPos).ToLower() ;

            Image _image;
            if (ExpandName == ".uitex")
            {
                int nFileNamePos = strFileName.LastIndexOf("\\");
                _image = uitex2img(strFileName.Substring(0, nFileNamePos), strFileName, nFrame);
            }
            else if (ExpandName == ".tga")
            {
                Paloma.TargaImage tgaImage = new Paloma.TargaImage(strFileName);
                _image = tgaImage.Image;
            }
            else
            {
                MessageBox.Show("错误的文件扩展名。");
                return string.Empty;
            }
            
            StringBuilder _rtf = new StringBuilder();

            using (Graphics _graphics = CurControl.CreateGraphics())
            {
                xDpi = _graphics.DpiX;
                yDpi = _graphics.DpiY;
            }
            _rtf.Append(RTF_HEADER);
            _rtf.Append(GetFontTable());
            _rtf.Append(GetImagePrefix(_image));
            _rtf.Append(GetRtfImage(_image, CurControl));
            _rtf.Append(RTF_IMAGE_POST);

            return _rtf.ToString();
        }
Example #40
0
        private static string GetRtfImage(Image _image, Control CurControl) 
        {
            StringBuilder _rtf = null;

            // Used to store the enhanced metafile
            MemoryStream _stream = null;

            // Used to create the metafile and draw the image
            Graphics _graphics = null;

            // The enhanced metafile
            Metafile _metaFile = null;

            // Handle to the device context used to create the metafile
            IntPtr _hdc;

            try 
            {
                _rtf = new StringBuilder();
                _stream = new MemoryStream();

                // Get a graphics context from the RichTextBox
                using (_graphics = CurControl.CreateGraphics()) 
                {

                    // Get the device context from the graphics context
                    _hdc = _graphics.GetHdc();

                    // Create a new Enhanced Metafile from the device context
                    _metaFile = new Metafile(_stream, _hdc);

                    // Release the device context
                    _graphics.ReleaseHdc(_hdc);
                }
            
                using(_graphics = Graphics.FromImage(_metaFile)) 
                {

                    // Draw the image on the Enhanced Metafile
                    _graphics.DrawImage(_image, new Rectangle(0, 0, _image.Width, _image.Height));
                }
                IntPtr _hEmf = _metaFile.GetHenhmetafile();

                // A call to EmfToWmfBits with a null buffer return the size of the
                // buffer need to store the WMF bits.  Use this to get the buffer
                // size.
                uint _bufferSize = GdipEmfToWmfBits(_hEmf, 0, null, MM_ANISOTROPIC,
                EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);

                // Create an array to hold the bits
                byte[] _buffer = new byte[_bufferSize];

                // A call to EmfToWmfBits with a valid buffer copies the bits into the
                // buffer an returns the number of bits in the WMF.  
                uint _convertedSize = GdipEmfToWmfBits(_hEmf, _bufferSize, _buffer, MM_ANISOTROPIC,
                EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);

                // Append the bits to the RTF string
                for(int i = 0; i < _buffer.Length; ++i) 
                {
                    _rtf.Append(String.Format("{0:X2}", _buffer[i]));
                }

                return _rtf.ToString();
            }
            finally 
            {
                if(_graphics != null)
                _graphics.Dispose();
                if(_metaFile != null)
                _metaFile.Dispose();
                if(_stream != null)
                _stream.Close();
            }
        }
Example #41
0
        /// <summary>
        ///  Plays back ink data to a specified control
        /// </summary>
        /// <param name="destinationControl">
        /// The control to play the Ink Data to.</param>           
        /// <param name="destinationRenderer">
        /// The Ink Renderer used to convert ink data to display coordinates</param>        
        /// <param name="keepDestinationAspectRatio">
        /// Specified whether to keep original aspect ratio of ink when scaling</param>
        /// <param name="playbackRate">
        /// The rate at which to play back the Ink Data</param>
        protected void PlaybackRecordedData( Control destinationControl,  
            bool keepDestinationAspectRatio,
            PacketPlaybackRate playbackRate,
            System.Drawing.Drawing2D.Matrix iTrans)
        {
            if( null != PlaybackInk ) {
                System.Drawing.Graphics g = destinationControl.CreateGraphics();
                Microsoft.Ink.Renderer destinationRenderer = new Microsoft.Ink.Renderer();
                destinationRenderer.SetViewTransform( iTrans );

                // Set whether or not to keep ink aspect ratio in the display window
                bool keepAspectRatio = keepDestinationAspectRatio;

                // Declare scaling factors
                float scaleFactorX = 1.0f;
                float scaleFactorY = 1.0f;

                // Get the size of the display window
                System.Drawing.Size displayWindowSize = destinationControl.ClientSize;

                // Get ink bounding box in ink space; convert the box's size to pixel;
                System.Drawing.Rectangle inkBoundingBox = PlaybackInk.GetBoundingBox();

                // Set the size and offset of the destination input
                System.Drawing.Point inkBoundingBoxSize = new System.Drawing.Point(inkBoundingBox.Width, inkBoundingBox.Height);

                // Convert the inkspace coordinate to pixels
                destinationRenderer.InkSpaceToPixel(g, ref inkBoundingBoxSize);

                // Get the offset of ink
                System.Drawing.Point inkOffset = inkBoundingBox.Location;

                // Determine what the scaling factor of the destination control is so
                // we know how to correctly resize the ink data
                getDisplayWindowScalingFactor(new System.Drawing.Size(inkBoundingBoxSize), displayWindowSize, keepAspectRatio, ref scaleFactorX, ref scaleFactorY);

                // Iterate through all ink strokes and extract the packet data
                foreach ( Microsoft.Ink.Stroke currentStroke in PlaybackInk.Strokes ) {
                    // Convert the stroke's packet data to INPUT structs
                    INPUT[] inputs = SendInputInterop.StrokeToInputs( currentStroke, destinationRenderer, g, scaleFactorX, scaleFactorY, destinationControl, inkOffset );

                    if ( null != inputs ) {
                        // Iterate through all the extracted INPUT data in order to send to destination control
                        for ( int i = 0; i < inputs.Length; i++ ) {
                            // Use the Win32 SendInput API to send the ink data point to the control
                            // Note that all playback will use the upper left of the destination control
                            // as the origin
                            SendInputInterop.SendInput( 1, new INPUT[] { inputs[i] }, System.Runtime.InteropServices.Marshal.SizeOf( inputs[i] ) );

                            // Determine the delay between packets (within a stroke)
                            switch( playbackRate ) {
                                case PacketPlaybackRate.Default:
                                default:
                                    System.Threading.Thread.Sleep(5);
                                    break;
                                case PacketPlaybackRate.Slow:
                                    System.Threading.Thread.Sleep(100);
                                    break;
                                case PacketPlaybackRate.Fast:
                                    break;
                            }
                        }
                    }

                    // Reset the focus to the destination control in case it has been changed
                    if( destinationControl.InvokeRequired ) {
                        GenericVoidCallback func = new GenericVoidCallback( delegate { destinationControl.Focus();  } );
                        destinationControl.Invoke( func );
                    } else
                        destinationControl.Focus();

                    // Create a delay between each stroke
                    if ( 0 != InterStrokeDelay) {
                        System.Threading.Thread.Sleep((int)(InterStrokeDelay));
                    }
                }
                // dispose the graphics object
                g.Dispose();
            }
        }
Example #42
0
        // TODO: Localize this!

        /// <summary> Calculates the average character width for the font of a given control. </summary>
        public static int GetAverageCharPixelWidth(WinForms.Control control)
        {
            using (Graphics graphics = control.CreateGraphics())
                return((int)(graphics.MeasureString(AverageChars, control.Font).Width / (float)AverageChars.Length));
        }
Example #43
0
 public static object CallControlCreateGraphics(Control c, object[] obj)
 {
     return(c.CreateGraphics());
 }
Example #44
0
 public WayPainter(System.Windows.Forms.Control fr)
 {
     this.Canvas    = fr;
     this._graphic  = fr.CreateGraphics();
     this.IsRunning = true;
 }