Ejemplo n.º 1
0
        SortedDictionary <uint, int> GetKerningPairs(Graphics g, GdiFont font, Dictionary <char, BnoerjGlyph> glyphs, ContentProcessorContext context)
        {
            // The kerning value is therefore proportional to the em-height.
            // To convert it to a real value you must divide the font's absolute
            // height in points or pixels by the em-height and then multiply by
            // the kerning value.
            // GetKerningPairs() returns the converted values.

            SortedDictionary <uint, int> kernings = new SortedDictionary <uint, int>();
            IntPtr hDC   = g.GetHdc();
            IntPtr hFont = NativeMethods.Gdi32.SelectObject(hDC, font.ToHfont());

            uint pairCount = NativeMethods.Gdi32.GetKerningPairs(hDC, 0, null);

            NativeMethods.Gdi32.KERNINGPAIR[] kerningPairs = new NativeMethods.Gdi32.KERNINGPAIR[pairCount];
            NativeMethods.Gdi32.GetKerningPairs(hDC, pairCount, kerningPairs);

            foreach (NativeMethods.Gdi32.KERNINGPAIR pair in kerningPairs)
            {
                BnoerjGlyph glyph;
                if (pair.iKernAmount != 0 &&
                    glyphs.TryGetValue((char)pair.wFirst, out glyph) == true &&
                    glyphs.TryGetValue((char)pair.wSecond, out glyph) == true)
                {
                    uint kerningKey = ((uint)pair.wFirst) << 16 | (uint)pair.wSecond;
                    kernings.Add(kerningKey, pair.iKernAmount);
                }
            }

            context.Logger.LogMessage("Kerning pairs: using {0} of {1}", kernings.Count, pairCount);
            NativeMethods.Gdi32.SelectObject(hDC, hFont);
            g.ReleaseHdc(hDC);

            return(kernings);
        }
Ejemplo n.º 2
0
		public static Size GetTextSize(Graphics graphics, string text, Font font)
		{
			IntPtr hdc = IntPtr.Zero;
			if ( graphics != null )
			{
				// Get device context from the graphics passed in
				hdc = graphics.GetHdc();
			}
			else
			{
				// Get screen device context
				hdc = WindowsAPI.GetDC(IntPtr.Zero);
			}

			IntPtr fontHandle = font.ToHfont();
			IntPtr currentFontHandle = WindowsAPI.SelectObject(hdc, fontHandle);

			Win32.RECT rect = new Win32.RECT();
			rect.left = 0;
			rect.right = 0;
			rect.top = 0;
			rect.bottom = 0;

			WindowsAPI.DrawText(hdc, text, text.Length, ref rect,
				(int)(DrawTextFormatFlags.DT_SINGLELINE | DrawTextFormatFlags.DT_LEFT | DrawTextFormatFlags.DT_CALCRECT));
			WindowsAPI.SelectObject(hdc, currentFontHandle);
			WindowsAPI.DeleteObject(fontHandle);

			if ( graphics != null )
				graphics.ReleaseHdc(hdc);
			else
				WindowsAPI.ReleaseDC(IntPtr.Zero, hdc);

			return new Size(rect.right - rect.left, rect.bottom - rect.top);
		}
Ejemplo n.º 3
0
            private TEXTMETRIC GenerateTextMetrics(
                Graphics graphics,
                Font font)
            {
                IntPtr     hDC = IntPtr.Zero;
                TEXTMETRIC textMetric;
                IntPtr     hFont = IntPtr.Zero;

                try
                {
                    hDC   = graphics.GetHdc();
                    hFont = font.ToHfont();
                    IntPtr hFontDefault = SelectObject(hDC, hFont);
                    bool   result       = GetTextMetrics(hDC, out textMetric);
                    SelectObject(hDC, hFontDefault);
                }
                finally
                {
                    if (hFont != IntPtr.Zero)
                    {
                        DeleteObject(hFont);
                    }
                    if (hDC != IntPtr.Zero)
                    {
                        graphics.ReleaseHdc(hDC);
                    }
                }
                return(textMetric);
            }
Ejemplo n.º 4
0
		/// <summary>
		/// Check if the font has a fixed width
		/// </summary>
		/// <param name="font">Font to check</param>
		/// <returns>true if the font has a fixed width</returns>
		public static bool IsFixedPitch(Font font)
		{
			bool result;

			IntPtr fnt = font.ToHfont();

			using (Bitmap bmp = new Bitmap(1, 1))
			{
				using (Graphics g = Graphics.FromImage(bmp))
				{
					IntPtr hdc = g.GetHdc();

					// store the current font and set the new one
					IntPtr fntOld = SelectObject(hdc, fnt);

					TEXTMETRIC metric = new TEXTMETRIC();

					NativeMethods.GetTextMetrics(hdc, ref metric);

					result = (metric.tmPitchAndFamily & TMPF_FIXED_PITCH) == 0;

					// restore the old font
					SelectObject(hdc, fntOld);

					g.ReleaseHdc(hdc);
				}
			}

			DeleteObject(fnt);

			return result;
		}
Ejemplo n.º 5
0
        // Methods
        public TextPainter(Control Control)
        {
            this.oldMode    = 1;
            this.bufferSize = 0;
            this.control    = Control;
            this.fontTable  = new Hashtable();
            this.brushTable = new Hashtable();
            this.penTable   = new Hashtable();
            IntPtr ptr1 = Win32.GetDC(IntPtr.Zero);

            System.Drawing.Font font1 = new System.Drawing.Font(FontFamily.GenericMonospace, 10f);
            try
            {
                this.measureDC      = Win32.CreateCompatibleDC(ptr1);
                this.oldMeasureFont = Win32.SelectObject(this.measureDC, font1.ToHfont());
            }
            finally
            {
                Win32.ReleaseDC(IntPtr.Zero, ptr1);
            }
            this.Font     = font1;
            this.Color    = Consts.DefaultControlForeColor;
            this.BkColor  = Consts.DefaultControlBackColor;
            this.PenColor = Consts.DefaultControlForeColor;
            this.bkMode   = 2;
        }
Ejemplo n.º 6
0
        public static List <FontRange> GetUnicodeRangesForFont(this sd.Font font)
        {
            var    g        = sd.Graphics.FromHwnd(IntPtr.Zero);
            IntPtr hdc      = g.GetHdc();
            IntPtr hFont    = font.ToHfont();
            IntPtr old      = SelectObject(hdc, hFont);
            uint   size     = GetFontUnicodeRanges(hdc, IntPtr.Zero);
            IntPtr glyphSet = Marshal.AllocHGlobal((int)size);

            GetFontUnicodeRanges(hdc, glyphSet);
            List <FontRange> fontRanges = new List <FontRange>();
            int count = Marshal.ReadInt32(glyphSet, 12);

            for (int i = 0; i < count; i++)
            {
                FontRange range = new FontRange();
                range.Low  = (UInt16)Marshal.ReadInt16(glyphSet, 16 + i * 4);
                range.High = (UInt16)(range.Low + Marshal.ReadInt16(glyphSet, 18 + i * 4) - 1);
                fontRanges.Add(range);
            }
            SelectObject(hdc, old);
            Marshal.FreeHGlobal(glyphSet);
            g.ReleaseHdc(hdc);
            g.Dispose();
            return(fontRanges);
        }
Ejemplo n.º 7
0
		public static Size GetTextSize(Graphics graphics, string text, Font font, ref Rectangle rc, DrawTextFormatFlags drawFlags)
		{
			IntPtr hdc = IntPtr.Zero;
			if ( graphics != null )
			{
				// Get device context from the graphics passed in
				hdc = graphics.GetHdc();
			}
			else
			{
				// Get screen device context
				hdc = WindowsAPI.GetDC(IntPtr.Zero);
			}

			IntPtr fontHandle = font.ToHfont();
			IntPtr currentFontHandle = WindowsAPI.SelectObject(hdc, fontHandle);

			Win32.RECT rect = new Win32.RECT();
			rect.left = rc.Left;
			rect.right = rc.Right;
			rect.top = rc.Top;
			rect.bottom = rc.Bottom;

			WindowsAPI.DrawText(hdc, text, text.Length, ref rect, (int)drawFlags);
			WindowsAPI.SelectObject(hdc, currentFontHandle);
			WindowsAPI.DeleteObject(fontHandle);

			if ( graphics != null )
				graphics.ReleaseHdc(hdc);
			else
				WindowsAPI.ReleaseDC(IntPtr.Zero, hdc);

			return new Size(rect.right - rect.left, rect.bottom - rect.top);

		}
Ejemplo n.º 8
0
 /// <summary>
 /// Creates a new CodepointRange object for a font.
 /// </summary>
 public CodepointRange(Font font)
 {
     List<char> rangeList = new List<char>();
     Graphics g = Graphics.FromImage(new Bitmap(1, 1));
     IntPtr hdc = g.GetHdc();
     IntPtr hFont = font.ToHfont();
     IntPtr oldFont = SelectObject(hdc, hFont);
     uint size = GetFontUnicodeRanges(hdc, IntPtr.Zero);
     IntPtr glyphSet = Marshal.AllocHGlobal((int)size);
     GetFontUnicodeRanges(hdc, glyphSet);
     codepointCount = Marshal.ReadInt32(glyphSet, 8);
     int tmp = 0;
     int count = Marshal.ReadInt32(glyphSet, 12);
     for (int i = 0; i < count; i++)
     {
         char firstIncluded = (char)Marshal.ReadInt16(glyphSet, 16 + i * 4);
         char firstExcluded = (char)(firstIncluded + Marshal.ReadInt16(glyphSet, 18 + i * 4));
         tmp += firstExcluded - firstIncluded;
         rangeList.Add(firstIncluded);
         rangeList.Add(firstExcluded);
     }
     SelectObject(hdc, oldFont);
     DeleteObject(hFont);
     Marshal.FreeHGlobal(glyphSet);
     g.ReleaseHdc(hdc);
     g.Dispose();
     if (tmp != codepointCount) throw new Exception(font.FontFamily.Name);
     ranges = rangeList.ToArray();
     if (ranges.Length < 2) throw new Exception();
 }
Ejemplo n.º 9
0
        public GdiTextureFont(int width, int height, System.Drawing.Font font, PixelFarm.Drawing.FontInfo fontInfo)
        {
            //if (this.dbugId == 2)
            //{

            //}

            this.width        = width;
            this.height       = height;
            this.textureAtlas = new TextureAtlas(width, height);
            this.hFont        = font.ToHfont();
            //32 bits bitmap
            textBoardBmp = new System.Drawing.Bitmap(textBoardW, textBoardH, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            gx           = System.Drawing.Graphics.FromImage(textBoardBmp);
            //draw character map
            //basic eng
            this.fontInfo = fontInfo;
            char[] chars = new char[255];
            for (int i = 0; i < 255; ++i)
            {
                chars[i] = (char)i;
            }
            //PrepareCharacterMap("ญู".ToCharArray());
            PrepareCharacterMapBlackOnWhite(chars);
            MakeTransparentOnWhite(textBoardBmp);

            //PrepareCharacterMapWhiteOnBlack(chars);
            //MakeTransparentOnBlack(textBoardBmp);
            //------------------
#if DEBUG
            //save bmp for debug
            //textBoardBmp.Save("d:\\WImageTest\\font_" + dbugId + ".png");
#endif
            //-------------------
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Measure a multiline string
        /// </summary>
        public static Size MeasureString(Graphics gr, Font font, string text, int width)
        {
            if (text == null) return new Size(1, 1);

            Rect bounds = new Rect() { Left = 0, Right = width, Bottom = 1, Top = 0 };
            IntPtr hDc = gr.GetHdc();
            try
            {
                int flags = DTCALCRECT | DTWORDBREAK;
                IntPtr controlFont = font.ToHfont();
                IntPtr originalObject = SelectObject(hDc, controlFont);
                try
                {
                    DrawText(hDc, text, text.Length, ref bounds, flags);
                }
                finally
                {
                    SelectObject(hDc, originalObject); // Release resources
                }
            }
            finally
            {
                gr.ReleaseHdc(hDc);
            }

            return new Size(bounds.Right - bounds.Left, bounds.Bottom - bounds.Top);
        }
Ejemplo n.º 11
0
        /*
           * get unicode font ranges
           */
        public static List<FontRange> GetFontUnicodeRanges(Font font)
        {
            Graphics g = Graphics.FromHwnd(IntPtr.Zero);
              IntPtr hdc = g.GetHdc();
              IntPtr hFont = font.ToHfont();
              IntPtr old = SelectObject(hdc, hFont);
              uint size = GetFontUnicodeRanges(hdc, IntPtr.Zero);
              IntPtr glyphSet = Marshal.AllocHGlobal((int)size);
              GetFontUnicodeRanges(hdc, glyphSet);
              List<FontRange> fontRanges = new List<FontRange>();
              int count = Marshal.ReadInt32(glyphSet, 12);

              for (int i = 0; i < count; i++)
              {
            FontRange range = new FontRange();
            range.Low = (UInt16)Marshal.ReadInt16(glyphSet, 16 + i * 4);
            range.High = (UInt16)(range.Low + Marshal.ReadInt16(glyphSet, 18 + i * 4) - 1);
            fontRanges.Add(range);
              }

              SelectObject(hdc, old);
              Marshal.FreeHGlobal(glyphSet);
              g.ReleaseHdc(hdc);
              g.Dispose();
              return fontRanges;
        }
Ejemplo n.º 12
0
		public static Size GetTextSize(Graphics graphics, string text, Font font)
		{
			IntPtr hdc = IntPtr.Zero;
			if ( graphics != null )
			{
				// Get device context from the graphics passed in
				hdc = graphics.GetHdc();
			}
			else
			{
				// Get screen device context
                hdc = APIsGdi.GetDC(IntPtr.Zero);
			}

			IntPtr fontHandle = font.ToHfont();
			IntPtr currentFontHandle = APIsGdi.SelectObject(hdc, fontHandle);
			
			APIsStructs.RECT rect = new APIsStructs.RECT();
			rect.left = 0;
			rect.right = 0;
			rect.top = 0;
			rect.bottom = 0;
		
			APIsUser32.DrawText(hdc, text, text.Length, ref rect, 
				APIsEnums.DrawTextFormatFlags.SINGLELINE | APIsEnums.DrawTextFormatFlags.LEFT | APIsEnums.DrawTextFormatFlags.CALCRECT);
			APIsGdi.SelectObject(hdc, currentFontHandle);
			APIsGdi.DeleteObject(fontHandle);

			if(graphics != null)
				graphics.ReleaseHdc(hdc);
			else
				APIsUser32.ReleaseDC(IntPtr.Zero, hdc);
							
			return new Size(rect.right - rect.left, rect.bottom - rect.top);
		}
Ejemplo n.º 13
0
        public void DrawText(string text, Point point, Font font, Color foreColor)
        {
            IntPtr fontHandle = font.ToHfont();
            IntPtr oldFontHandle = NativeMethods.SelectObject(this.graphicsHandle, fontHandle);

            int oldBkMode = NativeMethods.SetBkMode(this.graphicsHandle, NativeMethods.TRANSPARENT);
            int oldTextColor = NativeMethods.SetTextColor(this.graphicsHandle, Color.FromArgb(0, foreColor.R, foreColor.G, foreColor.B).ToArgb());

            Size size = this.MeassureTextInternal(text);

            NativeMethods.RECT clip = new NativeMethods.RECT();
            clip.left = point.X;
            clip.top = point.Y;
            clip.right = clip.left + size.Width;
            clip.bottom = clip.top + size.Height;

            // ExtTextOut does not show Mnemonics highlighting.
            NativeMethods.DrawText(this.graphicsHandle, text, text.Length, ref clip, NativeMethods.DT_SINGLELINE | NativeMethods.DT_LEFT);

            NativeMethods.SetTextColor(this.graphicsHandle, oldTextColor);
            NativeMethods.SetBkMode(this.graphicsHandle, oldBkMode);

            NativeMethods.SelectObject(this.graphicsHandle, oldFontHandle);
            NativeMethods.DeleteObject(fontHandle);
        }
 Win32.TEXTMETRIC GetTextMetrics(Font f)
 {
     Win32.TEXTMETRIC t;
     IntPtr hdc = Win32.GetDC(Handle);
     Win32.SelectObject(hdc, f.ToHfont());
     Win32.GetTextMetrics(hdc, out t);
     return t;
 }
Ejemplo n.º 15
0
		public KerningHelper( Font font )
		{
			dc = CreateCompatibleDC( IntPtr.Zero );
			if( dc == IntPtr.Zero )
				throw new System.ComponentModel.Win32Exception();

			hFont = font.ToHfont();			
			oldFont = SelectObject( dc, hFont );
		}
Ejemplo n.º 16
0
        /// <summary>
        /// Get pointer to unmanaged Hfont object for the given managed font object.
        /// </summary>
        /// <param name="font">the font to get unmanaged font for</param>
        /// <returns>Hfont pointer</returns>
        public static IntPtr GetCachedHFont(System.Drawing.Font font)
        {
            IntPtr hFont;

            if (!_fontsUnmanagedCache.TryGetValue(font, out hFont))
            {
                _fontsUnmanagedCache[font] = hFont = font.ToHfont();
            }
            return(hFont);
        }
Ejemplo n.º 17
0
        public Font(string filename, int size, FontStyle style)
        {
//			Debug.Assert(false);
            string fontname = filename.Replace("/Application/", "./");

            this.__size  = size;
            this.__style = style;
            System.Drawing.FontStyle _style = System.Drawing.FontStyle.Regular;
            switch (style)
            {
            case FontStyle.Regular:
                _style = System.Drawing.FontStyle.Regular;
                break;

            case FontStyle.Bold:
                _style = System.Drawing.FontStyle.Bold;
                break;

            case FontStyle.Italic:
                _style = System.Drawing.FontStyle.Italic;
                break;
            }
            PrivateFontCollection privateFonts = new PrivateFontCollection();

            privateFonts.AddFontFile(fontname);

            //Arial
            //Comic Sans MS
            //MS Gothic
            this.__font = new System.Drawing.Font(privateFonts.Families[0], (int)(__size * 0.75f), _style);             //FIXME:???0.8
            //this.__font = new System.Drawing.Font("Arial", __size, _style); //FIXME:???0.8
            //this.__font = new System.Drawing.Font(/*"宋体"*/FontFamily.GenericSansSerif, __size, _style);

            this.__metrics = new FontMetrics();


            IntPtr hdc    = GetDC(IntPtr.Zero);
            IntPtr handle = __font.ToHfont();

            try
            {
                IntPtr     handle2    = SelectObject(hdc, handle);
                TEXTMETRIC tEXTMETRIC = new TEXTMETRIC();
                GetTextMetrics(hdc, ref tEXTMETRIC);
                __metrics.Ascent  = tEXTMETRIC.tmAscent;
                __metrics.Descent = tEXTMETRIC.tmDescent;
                __metrics.Leading = tEXTMETRIC.tmHeight - tEXTMETRIC.tmAscent - tEXTMETRIC.tmDescent;
                SelectObject(hdc, handle2);
            }
            finally
            {
                DeleteObject(handle);
                ReleaseDC(IntPtr.Zero, hdc);
            }
        }
Ejemplo n.º 18
0
        static byte[] ReadFontBytesFromGdi(GdiFont gdiFont)
        {
            // Weird: LastError is always 123 or 127. Comment out Debug.Assert.
            int error = Marshal.GetLastWin32Error();

            //Debug.Assert(error == 0);
            error = Marshal.GetLastWin32Error();
            //Debug.Assert(error == 0);

            IntPtr hfont = gdiFont.ToHfont();
            IntPtr hdc   = NativeMethods.GetDC(IntPtr.Zero);

            error = Marshal.GetLastWin32Error();
            //Debug.Assert(error == 0);

            IntPtr oldFont = NativeMethods.SelectObject(hdc, hfont);

            error = Marshal.GetLastWin32Error();
            //Debug.Assert(error == 0);

            // Get size of the font file.
            bool isTtcf = false;
            // In Azure I get 0xc0000022
            int size = NativeMethods.GetFontData(hdc, 0, 0, null, 0);

            // Check for ntstatus.h: #define STATUS_ACCESS_DENIED             ((NTSTATUS)0xC0000022L)
            if ((uint)size == 0xc0000022)
            {
                throw new InvalidOperationException("Microsoft Azure returns STATUS_ACCESS_DENIED ((NTSTATUS)0xC0000022L) from GetFontData. This is a bug in Azure. You must implement a FontResolver to circumvent this issue.");
            }

            if (size == NativeMethods.GDI_ERROR)
            {
                // Assume that the font file is a true type collection.
                size   = NativeMethods.GetFontData(hdc, ttcf, 0, null, 0);
                isTtcf = true;
            }
            error = Marshal.GetLastWin32Error();
            //Debug.Assert(error == 0);

            if (size == 0)
            {
                throw new InvalidOperationException("Cannot retrieve font data.");
            }

            byte[] bytes         = new byte[size];
            int    effectiveSize = NativeMethods.GetFontData(hdc, isTtcf ? ttcf : 0, 0, bytes, size);

            Debug.Assert(size == effectiveSize);
            // Clean up.
            NativeMethods.SelectObject(hdc, oldFont);
            NativeMethods.ReleaseDC(IntPtr.Zero, hdc);

            return(bytes);
        }
Ejemplo n.º 19
0
        public static void DrawText(Graphics graphics, string text, Font font, Rectangle bounds, Color color, TextFormatFlags flags, TextStyle textStyle)
        {
            if (!VisualStyleRenderer.IsSupported) {
                TextRenderer.DrawText(graphics, text, font, bounds, color, flags);
                return;
            }

            IntPtr primaryHdc = graphics.GetHdc();

            // Create a memory DC so we can work offscreen
            IntPtr memoryHdc = CreateCompatibleDC(primaryHdc);

            // Create a device-independent bitmap and select it into our DC
            BITMAPINFO info = new BITMAPINFO();
            info.biSize = Marshal.SizeOf(info);
            info.biWidth = bounds.Width;
            info.biHeight = -bounds.Height;
            info.biPlanes = 1;
            info.biBitCount = 32;
            info.biCompression = 0; // BI_RGB
            IntPtr dib = CreateDIBSection(primaryHdc, info, 0, 0, IntPtr.Zero, 0);
            SelectObject(memoryHdc, dib);

            // Create and select font
            IntPtr fontHandle = font.ToHfont();
            SelectObject(memoryHdc, fontHandle);

            // Draw glowing text
            VisualStyleRenderer renderer = new VisualStyleRenderer(System.Windows.Forms.VisualStyles.VisualStyleElement.Window.Caption.Active);
            DTTOPTS dttOpts = new DTTOPTS();
            dttOpts.dwSize = Marshal.SizeOf(typeof(DTTOPTS));

            if (textStyle == TextStyle.Glowing) {
                dttOpts.dwFlags = DTT_COMPOSITED | DTT_GLOWSIZE | DTT_TEXTCOLOR;
            }
            else {
                dttOpts.dwFlags = DTT_COMPOSITED | DTT_TEXTCOLOR;
            }
            dttOpts.crText = ColorTranslator.ToWin32(color);
            dttOpts.iGlowSize = 8; // This is about the size Microsoft Word 2007 uses
            RECT textBounds = new RECT(0, 0, bounds.Right - bounds.Left, bounds.Bottom - bounds.Top);
            DrawThemeTextEx(renderer.Handle, memoryHdc, 0, 0, text, -1, (int)flags, ref textBounds, ref dttOpts);

            // Copy to foreground
            const int SRCCOPY = 0x00CC0020;
            BitBlt(primaryHdc, bounds.Left, bounds.Top, bounds.Width, bounds.Height, memoryHdc, 0, 0, SRCCOPY);

            // Clean up
            DeleteObject(fontHandle);
            DeleteObject(dib);
            DeleteDC(memoryHdc);

            graphics.ReleaseHdc(primaryHdc);
        }
Ejemplo n.º 20
0
        PixelFarm.Drawing.FontInfo RegisterFont(System.Drawing.Font newFont, FontKey fontKey)
        {
            //from ...
            //1. http://msdn.microsoft.com/en-us/library/xwf9s90b%28v=vs.100%29.aspx
            //3.  Font metrics from http://msdn.microsoft.com/en-us/library/xwf9s90b(VS.71).aspx

            //2. http://stackoverflow.com/questions/1006069/how-do-i-get-the-position-of-the-text-baseline-in-a-label-and-a-numericupdown
            //cellHeight = font's ascent + descent
            //linespacing = cellHeight + external leading
            //em height (size)= cellHeight - internal leading

            //-------------------
            //evaluate this font, collect font matrix in pixel mode
            PixelFarm.Drawing.FontInfo fontInfo;
            if (!_fontInfoCache.TryGetValue(newFont, out fontInfo))
            {
                System.Drawing.FontFamily ff = newFont.FontFamily;

                int lineSpacing = ff.GetLineSpacing(newFont.Style);
                //font height is expensive call ****
                int fontHeight = newFont.Height;

                //convert descent

                float fontSize     = newFont.Size;
                int   fontEmHeight = newFont.FontFamily.GetEmHeight(newFont.Style);
                int   fontAscent   = newFont.FontFamily.GetCellAscent(newFont.Style);
                float descent      = newFont.FontFamily.GetCellDescent(newFont.Style);

                var myFont = new PixelFarm.Drawing.WinGdi.MyFont(newFont);
                fontInfo = new PixelFarm.Drawing.WinGdi.MyFontInfo(
                    myFont,
                    fontHeight,
                    (fontAscent * fontSize / fontEmHeight),
                    (descent * fontSize / fontEmHeight),
                    fontHeight * fontAscent / lineSpacing,
                    gdiFontHelper);
                myFont.SetFontInfo(fontInfo);
                //lineSpacing * newFont.FontFamily.GetCellAscent(newFont.Style) / linespace);


                //1. info
                _fontInfoCache.Add(newFont, fontInfo);
                _fontInfoCacheByFontKey.Add(fontKey, fontInfo);

                _fontsUnmanagedCache[newFont] = newFont.ToHfont();
                //2. line cache
                _fontHeightCache[newFont] = fontHeight;

                return(fontInfo);
            }
            return(fontInfo);
        }
Ejemplo n.º 21
0
        public Size MeasureText(string text, Font font)
        {
            IntPtr fontHandle = font.ToHfont();
            IntPtr oldFontHandle = NativeMethods.SelectObject(this.graphicsHandle, fontHandle);

            Size size = this.MeassureTextInternal(text);

            NativeMethods.SelectObject(this.graphicsHandle, oldFontHandle);
            NativeMethods.DeleteObject(fontHandle);

            return size;
        }
Ejemplo n.º 22
0
        public static TEXTMETRICW GetTextMetrics(this sd.Font font)
        {
            using (var graphics = new swf.Control().CreateGraphics())
            {
                var hDC = graphics.GetHdc();

                var hFont        = font.ToHfont();
                var hFontDefault = SelectObject(hDC, hFont);

                GetTextMetrics(hDC, out var textMetric);
                return(textMetric);
            }
        }
Ejemplo n.º 23
0
        public ChartDraw()
        {
            IntPtr dC = Win32.GetDC(IntPtr.Zero);

            System.Drawing.Font font = new System.Drawing.Font(FontFamily.GenericMonospace, 10f);
            try {
                this.measureDC      = Win32.CreateCompatibleDC(dC);
                this.measureHFont   = font.ToHfont();
                this.oldMeasureFont = Win32.SelectObject(this.measureDC, this.measureHFont);
            } finally {
                Win32.ReleaseDC(IntPtr.Zero, dC);
            }
            this.Init();
        }
Ejemplo n.º 24
0
        public static void DrawString(Control context, Font font, string text, Rectangle textBounds, bool useMnemonics, GdiTextDrawMode textMode)
        {
            IntPtr hdc = User32.GetDC(context.Handle);
            try
            {
                Gdi32.SetBkColor(hdc, Gdi32.ToColorRef(context.BackColor));
                Gdi32.SetTextColor(hdc, Gdi32.ToColorRef(context.ForeColor));

                try
                {
                    IntPtr hFont = font.ToHfont();
                    try
                    {
                        IntPtr hPrevFont = Gdi32.SelectObject(hdc, hFont);
                        try
                        {
                            StringBuilder sb = new StringBuilder(text);
                            RECT rect = textBounds;
                            User32.DRAWTEXTPARAMS dtparams = new User32.DRAWTEXTPARAMS();
                            dtparams.cbSize = (uint)Marshal.SizeOf(typeof(User32.DRAWTEXTPARAMS));
                            User32.DT flags =
                                textMode == GdiTextDrawMode.EndEllipsis ? User32.DT.END_ELLIPSIS
                                : textMode == GdiTextDrawMode.WordBreak ? User32.DT.WORDBREAK | User32.DT.END_ELLIPSIS
                                : User32.DT.WORDBREAK;
                            if (useMnemonics)
                                flags |= User32.DT.NOPREFIX;

                            if (0 == User32.DrawTextEx(hdc, sb, sb.Length, ref rect, flags, ref dtparams))
                                throw new Win32Exception(Marshal.GetLastWin32Error());
                        }
                        finally
                        {
                            Gdi32.SelectObject(hdc, hPrevFont);
                        }
                    }
                    finally
                    {
                        Gdi32.DeleteObject(hFont);
                    }
                }
                finally
                {
                }
            }
            finally
            {
                User32.ReleaseDC(context.Handle, hdc);
            }

        }
Ejemplo n.º 25
0
        public static bool ScriptPlace(System.Drawing.Font font, Uniscribe.SCRIPT_ITEM[] items,
                                       List <ushort[]> pwGlyphs, List <int> cGlyphs, List <Uniscribe.SCRIPT_VISATTR[]> psva,
                                       out List <int[]> piAdvanceArray, out List <Uniscribe.GOFFSET[]> pGoffsetArray, out List <Uniscribe.ABC> pABCArray)
        {
            piAdvanceArray = new List <int[]>();
            pGoffsetArray  = new List <Uniscribe.GOFFSET[]>();
            pABCArray      = new List <Uniscribe.ABC>();

            if (font == null)
            {
                return(false);
            }

            bool res = false;

            // HFONT hfont = initialize your font;
            IntPtr hfont = font.ToHfont();

            IntPtr psc = IntPtr.Zero; // Initialize to NULL, will be filled lazily.

            // Don't use the last item because it is a dummy that points
            // to the end of the string.
            for (int i = 0; i < items.Length - 1; i++)
            {
                int[] piAdvance;
                Uniscribe.GOFFSET[] pGoffset;
                Uniscribe.ABC       pABC;

                Uniscribe.SCRIPT_ANALYSIS sa = items[i].a;
                res = callScriptPlaceForItem(ref hfont, ref psc, pwGlyphs[i], cGlyphs[i], psva[i], ref sa, out piAdvance, out pGoffset, out pABC);

                if (res)
                {
                    items[i].a = sa;

                    piAdvanceArray.Add(piAdvance);
                    pGoffsetArray.Add(pGoffset);
                    pABCArray.Add(pABC);
                }
            }

            // Need to tell Uniscribe to delete the cache we were using. If you are going
            // to keep the HFONT around, you should probably also keep the cache.
            //             ScriptFreeCache(psc);

            Win32.DeleteObject(hfont);

            return(res);
        }
Ejemplo n.º 26
0
        private void vAdjustFontSize(System.Drawing.Font fntFonte)
        {
            PS    = new struct0E();
            PS.QR = 212;

            System.Drawing.Bitmap   bmp   = new System.Drawing.Bitmap(1, 1);
            System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(bmp);
            float fUnit = (72000f / graph.DpiX);

            System.Drawing.Font fntUnit = new System.Drawing.Font(fntFonte.Name, fUnit, fntFonte.Style, System.Drawing.GraphicsUnit.Point);
            System.IntPtr       ptr1    = graph.GetHdc();
            System.IntPtr       ptr2    = fntUnit.ToHfont();
            System.IntPtr       ptr3    = SelectObject(ptr1, ptr2);
            if (GetOutlineTextMetrics(ptr1, 212, ref PS) != 0)
            {
                ARIAL_W_ARRAY = new int[((uint)((PS.QS.Q5 - PS.QS.Q4) + 1))];
                if (System.Environment.OSVersion.Platform >= PlatformID.Win32NT)
                {
                    GetCharWidth32(ptr1, PS.QS.Q4, PS.QS.Q5, ARIAL_W_ARRAY);
                }
                else
                {
                    System.Drawing.Size       size1       = System.Drawing.Size.Empty;
                    System.Text.StringBuilder strbMeasure = new System.Text.StringBuilder();
                    for (int num1 = 0; (num1 < ARIAL_W_ARRAY.Length); num1 += 1)
                    {
                        strbMeasure.Length = 0;
                        strbMeasure.Append(((char)(PS.QS.Q4 + num1)));
                        GetTextExtentPoint32(ptr1, strbMeasure.ToString(), 1, ref size1);
                        ARIAL_W_ARRAY[num1] = size1.Width;
                    }
                }
            }
            bool flag1 = ((PS.QW & 1) == 0);

            if (flag1)
            {
                int num2 = GetFontData(ptr1, 0, 0, null, 0);
                //this.PQ = new byte[((uint) num2)];
                //GetFontData(ptr1, 0, 0, this.PQ, num2);
                //this.PR = new Y(this);
            }
            SelectObject(ptr1, ptr3);
            DeleteObject(ptr2);
            graph.ReleaseHdc(ptr1);
            fntUnit.Dispose();
            graph.Dispose();
            bmp.Dispose();
        }
Ejemplo n.º 27
0
        public Font(FontAlias alias, int size, FontStyle style)
        {
            this.__alias = alias;
            this.__size  = size;
            this.__style = style;
            System.Drawing.FontStyle _style = System.Drawing.FontStyle.Regular;
            switch (style)
            {
            case FontStyle.Regular:
                _style = System.Drawing.FontStyle.Regular;
                break;

            case FontStyle.Bold:
                _style = System.Drawing.FontStyle.Bold;
                break;

            case FontStyle.Italic:
                _style = System.Drawing.FontStyle.Italic;
                break;
            }
            //Arial
            //Comic Sans MS
            //MS Gothic
            this.__font = new System.Drawing.Font("MS Gothic", (int)(__size * 0.75f), _style);             //FIXME:???0.8
            //this.__font = new System.Drawing.Font("Arial", __size, _style); //FIXME:???0.8
            //this.__font = new System.Drawing.Font(/*"宋体"*/FontFamily.GenericSansSerif, __size, _style);

            this.__metrics = new FontMetrics();


            IntPtr hdc    = GetDC(IntPtr.Zero);
            IntPtr handle = __font.ToHfont();

            try
            {
                IntPtr     handle2    = SelectObject(hdc, handle);
                TEXTMETRIC tEXTMETRIC = new TEXTMETRIC();
                GetTextMetrics(hdc, ref tEXTMETRIC);
                __metrics.Ascent  = tEXTMETRIC.tmAscent;
                __metrics.Descent = tEXTMETRIC.tmDescent;
                __metrics.Leading = tEXTMETRIC.tmHeight - tEXTMETRIC.tmAscent - tEXTMETRIC.tmDescent;
                SelectObject(hdc, handle2);
            }
            finally
            {
                DeleteObject(handle);
                ReleaseDC(IntPtr.Zero, hdc);
            }
        }
Ejemplo n.º 28
0
        public static bool ScriptShape(string str, System.Drawing.Font font, Uniscribe.SCRIPT_ITEM[] items,
                                       out List <ushort[]> pwOutGlyphsArray, out List <int> cGlyphsArray, out List <Uniscribe.SCRIPT_VISATTR[]> psvaArray)
        {
            pwOutGlyphsArray = new List <ushort[]>();
            cGlyphsArray     = new List <int>();
            psvaArray        = new List <Uniscribe.SCRIPT_VISATTR[]>();

            if (font == null)
            {
                return(false);
            }

            bool res = false;

            // HFONT hfont = initialize your font;
            IntPtr hfont = font.ToHfont();

            IntPtr psc = IntPtr.Zero; // Initialize to NULL, will be filled lazily.

            // Don't use the last item because it is a dummy that points
            // to the end of the string.
            for (int i = 0; i < items.Length - 1; i++)
            {
                ushort[] pwOutGlyphs;
                ushort[] pwLogClust;
                Uniscribe.SCRIPT_VISATTR[] psva;

                int    length = items[i + 1].iCharPos - items[i].iCharPos; // Length of this run.
                string run    = str.Substring(items[i].iCharPos, length);  // Beginning of this run.

                res = callScriptShapeForItem(run, length, ref hfont, ref psc, items[i].a, out pwOutGlyphs, out pwLogClust, out psva);

                if (res)
                {
                    pwOutGlyphsArray.Add(pwOutGlyphs);
                    cGlyphsArray.Add(pwOutGlyphs.Length);
                    psvaArray.Add(psva);
                }
            }

            // Need to tell Uniscribe to delete the cache we were using. If you are going
            // to keep the HFONT around, you should probably also keep the cache.
//             ScriptFreeCache(psc);

            Win32.DeleteObject(hfont);

            return(res);
        }
Ejemplo n.º 29
0
    public static Size GetTextSize( Graphics g, string text, Font font )
    {
      IntPtr hdc = GetGraphicsHDC( g );
      
      IntPtr hFont = font.ToHfont();
      IntPtr hOldFont = WindowsAPI.SelectObject( hdc, hFont );
      
      RECT rect = new RECT();
      WindowsAPI.DrawText( hdc, text, text.Length, ref rect, DEF_TEXTFORMAT );
      WindowsAPI.SelectObject( hdc, hOldFont );
      WindowsAPI.DeleteObject( hFont );

      ReleaseGraphicHDC( g, hdc );

      return ( Size )rect;
    }
Ejemplo n.º 30
0
        /// <summary>
        /// Measure a multiline string
        /// </summary>
        public static Size MeasureString(Graphics gr, Font font, string text, int width)
        {
            try{
                Rect bounds = new Rect() { Left = 0, Right = width, Bottom = 1, Top = 0 };
                IntPtr hDc = gr.GetHdc();
                int flags = DTCALCRECT | DTWORDBREAK;
                IntPtr controlFont = font.ToHfont();
                IntPtr originalObject = SelectObject(hDc, controlFont);
                DrawText(hDc, text, text.Length, ref bounds, flags);
                SelectObject(hDc, originalObject); // Release resources
                gr.ReleaseHdc(hDc);

                return new Size(bounds.Right - bounds.Left, bounds.Bottom - bounds.Top);
            }catch(Exception){
                return Size.Empty;
            }
        }
Ejemplo n.º 31
0
        public Font(Document doc, string fontName, System.Drawing.Font winFont)
            : base(doc)
        {
            _fontName = fontName;

            //TBD - I have no idea why 720 seems to work.  I don't understand the relationship
            // between windows font coordinates and PDF glyph coordinates.  It seems like this
            // should be 1000, but that doesn't work.
            System.Drawing.Font f = new System.Drawing.Font(winFont.FontFamily, 720, winFont.Style, GraphicsUnit.Point);

            IntPtr hDC     = WinGdi.GetDC(IntPtr.Zero); //Screen DC
            IntPtr hObjOld = WinGdi.SelectObject(hDC, f.ToHfont());
            uint   cbSize  = WinGdi.GetOutlineTextMetrics(hDC, 0, IntPtr.Zero);

            if (cbSize == 0)
            {
                throw new Exception();
            }

            StringBuilder sb = new StringBuilder(50);

            WinGdi.GetTextFace(hDC, 50, sb);

            IntPtr buffer = Marshal.AllocHGlobal((int)cbSize);

            try
            {
                if (WinGdi.GetOutlineTextMetrics(hDC, cbSize, buffer) != 0)
                {
                    _otm          = (WinGdi.OUTLINETEXTMETRIC)Marshal.PtrToStructure(buffer, typeof(WinGdi.OUTLINETEXTMETRIC));
                    _faceName     = Marshal.PtrToStringAnsi((IntPtr)((long)buffer + _otm.pFaceName));
                    _faceName     = _faceName.Replace(" ", "-");
                    _otm.EMSquare = (uint)(_otm.EMSquare / winFont.SizeInPoints);
                }
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }

            _fw = new FontWidths(doc, hDC, _otm);
            _fd = new FontDescriptor(doc, _faceName, _otm);

            WinGdi.SelectObject(hDC, hObjOld);
            WinGdi.ReleaseDC(IntPtr.Zero, hDC);
        }
Ejemplo n.º 32
0
 public static TEXTMETRIC GetTextMetrics(Graphics graphics, Font font)
 {
     TEXTMETRIC textmetric;
     IntPtr hdc = graphics.GetHdc();
     IntPtr hgdiobj = font.ToHfont();
     try
     {
         IntPtr ptr3 = SelectObject(hdc, hgdiobj);
         bool textMetrics = GetTextMetrics(hdc, out textmetric);
         SelectObject(hdc, ptr3);
     }
     finally
     {
         DeleteObject(hgdiobj);
         graphics.ReleaseHdc(hdc);
     }
     return textmetric;
 }
Ejemplo n.º 33
0
        /// <summary>
        /// ��ȡָ���ַ���ָ�������µ�����
        /// </summary>
        /// <param name="uChar">�ַ�</param>
        /// <param name="font">����</param>
        /// <returns></returns>
        public static String GetOutline(uint uChar, Font font)
        {
            //����
            Graphics g = Graphics.FromHwnd(IntPtr.Zero);
            IntPtr hdc = g.GetHdc();

            //������ѡ�볡��
            IntPtr fontPtr = font.ToHfont();
            GdiNativeMethods.SelectObject(hdc, fontPtr);
            try
            {
                return GetOutline(hdc, uChar);
            }
            catch (Exception e)
            {
                Console.Write(e.Message);
                return "";
            }
        }
Ejemplo n.º 34
0
        bool CheckFontForEmbedding(Graphics g, GdiFont font, ContentProcessorContext context)
        {
            bool embeddingAllowed = false;

            IntPtr hDC   = g.GetHdc();
            IntPtr hFont = NativeMethods.Gdi32.SelectObject(hDC, font.ToHfont());

            uint cbSize = NativeMethods.Gdi32.GetOutlineTextMetrics(hDC, 0, IntPtr.Zero);

            if (cbSize == 0)
            {
                return(embeddingAllowed);
            }

            IntPtr buffer = Marshal.AllocHGlobal((int)cbSize);

            try
            {
                if (NativeMethods.Gdi32.GetOutlineTextMetrics(hDC, cbSize, buffer) != 0)
                {
                    NativeMethods.Gdi32.OUTLINETEXTMETRIC otm;
                    otm = (NativeMethods.Gdi32.OUTLINETEXTMETRIC)Marshal.PtrToStructure(buffer, typeof(NativeMethods.Gdi32.OUTLINETEXTMETRIC));

                    FontEmbeddingFlags fontEmbedding = (FontEmbeddingFlags)otm.otmfsType;
                    embeddingAllowed =
                        (fontEmbedding == FontEmbeddingFlags.Installable) ||
                        ((fontEmbedding & FontEmbeddingFlags.NotAllowed) == 0 &&
                         (fontEmbedding & FontEmbeddingFlags.Editable) != 0 ||
                         (fontEmbedding & FontEmbeddingFlags.BitmapOnly) != 0);
                    context.Logger.LogMessage("Embedding font {0} is {1} as {2}", font.Name, embeddingAllowed ? "allowed" : "not allowed", fontEmbedding.ToString());
                    context.Logger.LogMessage("Avg. width: {0}, Max. width: {1}", otm.otmTextMetrics.tmAveCharWidth, otm.otmTextMetrics.tmMaxCharWidth);
                }
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }

            NativeMethods.Gdi32.SelectObject(hDC, hFont);
            g.ReleaseHdc(hDC);

            return(embeddingAllowed);
        }
Ejemplo n.º 35
0
        public static TEXTMETRIC GetTextMetrics( Graphics graphics, Font font )
        {
            IntPtr hDC = graphics.GetHdc();
            TEXTMETRIC textMetric;
            IntPtr hFont = font.ToHfont();

            try
            {
                IntPtr hFontPreviouse = SelectObject(hDC, hFont);
                bool result = GetTextMetrics(hDC, out textMetric);
                SelectObject(hDC, hFontPreviouse);
            }
            finally
            {
                DeleteObject(hFont);
                graphics.ReleaseHdc(hDC);
            }

            return textMetric;
        }
Ejemplo n.º 36
0
        /// <summary>
        /// ��ȡָ���ַ���ָ�������µ�����
        /// </summary>
        /// <param name="uChar">�ַ�</param>
        /// <param name="font">����</param>
        /// <returns></returns>
        public static DOutline GetOutline(uint uChar, Font font)
        {
            //����
            Graphics g = Graphics.FromHwnd(IntPtr.Zero);
            IntPtr hdc = g.GetHdc();

            //������ѡ�볡��
            IntPtr fontPtr = font.ToHfont();
            GdiNativeMethods.SelectObject(hdc, fontPtr);
            try
            {
                return GetOutline(hdc, uChar);
            }
            finally
            {
                //�ر����������ͷų���
                GdiNativeMethods.CloseHandle(fontPtr);
                g.ReleaseHdc(hdc);
            }
        }
Ejemplo n.º 37
0
		public static Size GetTextSize(Graphics graphics, string text, Font font)
		{
			IntPtr hdc = graphics.GetHdc();
			IntPtr fontHandle = font.ToHfont();
			IntPtr currentFontHandle = WindowsAPI.SelectObject(hdc, fontHandle);
			
			RECT rect = new RECT();
			rect.left = 0;
			rect.right = 0;
			rect.top = 0;
			rect.bottom = 0;
		
			WindowsAPI.DrawText(hdc, text, text.Length, ref rect, 
				(int)(DrawTextFormatFlags.DT_SINGLELINE | DrawTextFormatFlags.DT_LEFT | DrawTextFormatFlags.DT_CALCRECT));
			WindowsAPI.SelectObject(hdc, currentFontHandle);
			WindowsAPI.DeleteObject(fontHandle);
			graphics.ReleaseHdc(hdc);
				
			return new Size(rect.right - rect.left, rect.bottom - rect.top);
		}
Ejemplo n.º 38
0
    public static Size GetTextSize( Graphics g, string text, Font font, ref Rectangle rc, DrawTextFormatFlags drawFlags )
    {
      IntPtr hdc = GetGraphicsHDC( g );
      IntPtr hFont = font.ToHfont();
      IntPtr hOldFont = WindowsAPI.SelectObject( hdc, hFont );
      
      Win32.RECT rect = new Win32.RECT();
      rect.left   = rc.Left;
      rect.right  = rc.Right;
      rect.top    = rc.Top;
      rect.bottom = rc.Bottom;
    
      WindowsAPI.DrawText( hdc, text, text.Length, ref rect, (int)drawFlags );
      WindowsAPI.SelectObject( hdc, hOldFont );
      WindowsAPI.DeleteObject( hFont );

      ReleaseGraphicHDC( g, hdc );
              
      return ( Size )rect;
    }
Ejemplo n.º 39
0
        public static void DrawText(Graphics graphics, string text, Font font, Rectangle rect)
        {
            IntPtr hdc = graphics.GetHdc();
              IntPtr fontHandle = font.ToHfont();
              IntPtr currentFontHandle = WindowsAPI.SelectObject(hdc, fontHandle);
              WindowsAPI.SetBkMode(hdc, BackgroundMode.TRANSPARENT);

              RECT rc = new RECT();
              rc.left = rect.Left;
              rc.top = rect.Top;
              rc.right = rc.left + rect.Width;
              rc.bottom = rc.top + rect.Height;

              WindowsAPI.DrawText(hdc, text, text.Length, ref rc,
                          (int) (DrawTextFormatFlags.DT_SINGLELINE | DrawTextFormatFlags.DT_LEFT
                                 | DrawTextFormatFlags.DT_MODIFYSTRING | DrawTextFormatFlags.DT_WORD_ELLIPSIS));
              WindowsAPI.SelectObject(hdc, currentFontHandle);
              WindowsAPI.DeleteObject(fontHandle);
              graphics.ReleaseHdc(hdc);
        }
Ejemplo n.º 40
0
        public ScriptMetrics SelectFont(Font font)
        {
            if (currentFont != font)
            {
                NativeMethods.SelectObject(HDC, font.ToHfont());
                currentFont = font;
                currentScriptMetrics = scriptMetricsCache[currentFont];

                if (!currentScriptMetrics.HaveMetrics)
                {
                    TEXTMETRIC textMetric;
                    NativeMethods.GetTextMetrics(HDC, out textMetric);

                    currentScriptMetrics.Height = textMetric.tmHeight;
                    currentScriptMetrics.Descent = textMetric.tmDescent;
                    currentScriptMetrics.HaveMetrics = true;
                }
            }
 
            return currentScriptMetrics;
        }
Ejemplo n.º 41
0
        // Calculate ABC spacing
        // http://msdn.microsoft.com/en-us/library/windows/desktop/dd162454(v=vs.85).aspx
        private static ABCSpacing CalculateABCSpacing(char character, Font font, Graphics stagingGraphics)
        {
            var hdc = stagingGraphics.GetHdc();

            try
            {
                var hFont = font.ToHfont();

                try
                {
                    var oldFont = GDI.SelectObject(hdc, hFont);

                    try
                    {
                        var abcSpacing = new ABCSpacing[1];
                        var result = GDI.GetCharABCWidthsFloat(hdc, character, character, abcSpacing);

                        if (!result)
                        {
                            throw new Exception("GetCharABCWidthsFloat failed!");
                        }

                        return abcSpacing[0];
                    }
                    finally
                    {
                        GDI.SelectObject(hdc, oldFont);
                    }
                }
                finally
                {
                    GDI.DeleteObject(hFont);
                }
            }
            finally
            {
                stagingGraphics.ReleaseHdc(hdc);
            }
        }
Ejemplo n.º 42
0
        public static Rectangle MeasureString(Control context, Font font, string text, Rectangle textBounds)
        {
            IntPtr hdc = User32.GetDC(context.Handle);
            try
            {
                IntPtr hFont = font.ToHfont();
                try
                {
                    IntPtr hPrevFont = Gdi32.SelectObject(hdc, hFont);
                    try
                    {
                        StringBuilder sb = new StringBuilder(text);
                        RECT rect = textBounds;
                        rect.bottom = rect.top; // set height to 0
                        User32.DRAWTEXTPARAMS dtparams = new User32.DRAWTEXTPARAMS();
                        dtparams.cbSize = (uint)Marshal.SizeOf(typeof(User32.DRAWTEXTPARAMS));
                        if (0 == User32.DrawTextEx(hdc, sb, sb.Length, ref rect, User32.DT.CALCRECT | User32.DT.WORDBREAK | User32.DT.END_ELLIPSIS, ref dtparams))
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        return rect;
                    }
                    finally
                    {
                        Gdi32.SelectObject(hdc, hPrevFont);
                    }
                }
                finally
                {
                    Gdi32.DeleteObject(hFont);
                }
            }
            finally
            {
                User32.ReleaseDC(context.Handle, hdc);
            }

        }
Ejemplo n.º 43
0
        public static bool ScriptTextOut(string filePathSave, System.Drawing.Font font, List <int> xArray, List <int> yArray, uint fuOptions, Win32.RECT lprc,
                                         List <Uniscribe.SCRIPT_ANALYSIS> psaArray, string pwcReserved, int iReserved,
                                         List <ushort[]> pwGlyphsArray, List <int> cGlyphsArray,
                                         List <int[]> piAdvanceArray, List <int[]> piJustifyArray, List <Uniscribe.GOFFSET[]> pGoffsetArray)
        {
            bool res = false;

            int width  = 500;
            int height = 400;

            System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, width, height);
            lprc = new Win32.RECT(rect);

            Bitmap   bitmap = null;
            Graphics gr     = null;
            IntPtr   HDC    = IntPtr.Zero;

            createBitmap(font, ref bitmap, width, height, ref gr);
            HDC = gr.GetHdc();

            // HFONT hfont = initialize your font;
            IntPtr hfont = font.ToHfont();

            // HFONT old_font = NULL;
            IntPtr old_font = IntPtr.Zero;

            // ... select font into hdc ...
            old_font = Win32.SelectObject(HDC, hfont);

            int old_color = 0;

            old_color = Win32.SetTextColor(HDC, ColorTranslator.ToWin32(System.Drawing.Color.Black));
            System.Drawing.Color color = ColorTranslator.FromWin32(old_color);
            old_color = Win32.SetBkColor(HDC, ColorTranslator.ToWin32(System.Drawing.Color.Yellow));
            color     = ColorTranslator.FromWin32(old_color);

            string text = "It's me!";

            Win32.RECT bounds = new Win32.RECT(rect);
            int        flags  = Win32.DT_CENTER | Win32.DT_VCENTER | Win32.DT_SINGLELINE;
            uint       result = 0;

            result = Win32.DrawText(HDC, text, text.Length, ref bounds, flags);

            IntPtr psc = IntPtr.Zero; // Initialize to NULL, will be filled lazily.

            for (int i = 0; i < psaArray.Count; i++)
            {
                res = callScriptTextOutForItem(HDC, psc, xArray[i], yArray[i], fuOptions, lprc, psaArray[i], pwcReserved,
                                               iReserved, pwGlyphsArray[i], cGlyphsArray[i], piAdvanceArray[i], piJustifyArray[i], pGoffsetArray[i]);

                if (!res)
                {
                }
            }

            if (old_font != IntPtr.Zero)
            {
                Win32.SelectObject(HDC, old_font);  // Put back the previous font.
            }
            gr.ReleaseHdc(HDC);
            saveBitmap(bitmap, gr, filePathSave);

            return(res);
        }
Ejemplo n.º 44
0
        public void DrawTextOnGlass(IntPtr hwnd, String text, Font font, Rectangle ctlrct, int iglowSize)
        {
            if (IsCompositionEnabled())
            {
                RECT rc = new RECT();
                RECT rc2 = new RECT();

                rc.left = ctlrct.Left;
                rc.right = ctlrct.Right + 2 * iglowSize;  //make it larger to contain the glow effect
                rc.top = ctlrct.Top;
                rc.bottom = ctlrct.Bottom + 2 * iglowSize;

                //Just the same rect with rc,but (0,0) at the lefttop
                rc2.left = 0;
                rc2.top = 0;
                rc2.right = rc.right - rc.left;
                rc2.bottom = rc.bottom - rc.top;

                IntPtr destdc = GetDC(hwnd);    //hwnd must be the handle of form,not control
                IntPtr Memdc = CreateCompatibleDC(destdc);   // Set up a memory DC where we'll draw the text.
                IntPtr bitmap;
                IntPtr bitmapOld = IntPtr.Zero;
                IntPtr logfnotOld;

                int uFormat = DT_SINGLELINE | DT_CENTER | DT_VCENTER | DT_NOPREFIX;   //text format

                BITMAPINFO dib = new BITMAPINFO();
                dib.bmiHeader.biHeight = -(rc.bottom - rc.top);         // negative because DrawThemeTextEx() uses a top-down DIB
                dib.bmiHeader.biWidth = rc.right - rc.left;
                dib.bmiHeader.biPlanes = 1;
                dib.bmiHeader.biSize = Marshal.SizeOf(typeof(BITMAPINFOHEADER));
                dib.bmiHeader.biBitCount = 32;
                dib.bmiHeader.biCompression = BI_RGB;
                if (!(SaveDC(Memdc) == 0))
                {
                    bitmap = CreateDIBSection(Memdc, ref dib, DIB_RGB_COLORS, 0, IntPtr.Zero, 0);   // Create a 32-bit bmp for use in offscreen drawing when glass is on
                    if (!(bitmap == IntPtr.Zero))
                    {
                        bitmapOld = SelectObject(Memdc, bitmap);
                        IntPtr hFont = font.ToHfont();
                        logfnotOld = SelectObject(Memdc, hFont);
                        try
                        {

                            System.Windows.Forms.VisualStyles.VisualStyleRenderer renderer = new System.Windows.Forms.VisualStyles.VisualStyleRenderer(System.Windows.Forms.VisualStyles.VisualStyleElement.Window.Caption.Active);

                            DTTOPTS dttOpts = new DTTOPTS();

                            dttOpts.dwSize = (uint)Marshal.SizeOf(typeof(DTTOPTS));

                            dttOpts.dwFlags = DTT_COMPOSITED | DTT_GLOWSIZE;

                            dttOpts.iGlowSize = iglowSize;

                            DrawThemeTextEx(renderer.Handle, Memdc, 0, 0, text, -1, uFormat, ref rc2, ref dttOpts);

                            BitBlt(destdc, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, Memdc, 0, 0, SRCCOPY);

                        }
                        catch (Exception e)
                        {
                            Trace.WriteLine(e.Message);
                        }

                        //Remember to clean up
                        SelectObject(Memdc, bitmapOld);
                        SelectObject(Memdc, logfnotOld);
                        DeleteObject(bitmap);
                        DeleteObject(hFont);

                        ReleaseDC(Memdc, -1);
                        DeleteDC(Memdc);

                    }

                }

            }
        }
Ejemplo n.º 45
0
        public static bool ScriptGetFontProperties(System.Drawing.Font font, out Uniscribe.SCRIPT_FONTPROPERTIES sfp)
        {
            sfp = new Uniscribe.SCRIPT_FONTPROPERTIES();

            if (font == null)
            {
                return(false);
            }

            // HFONT hfont = initialize your font;
            IntPtr hfont = font.ToHfont();

            IntPtr psc = IntPtr.Zero; // Initialize to NULL, will be filled lazily.

            IntPtr hdcSrc = IntPtr.Zero;
            IntPtr HDC    = IntPtr.Zero; // Don't give it a DC unless we have to.

            // HFONT old_font = NULL;
            IntPtr old_font = IntPtr.Zero;

            uint res = 0;

            sfp        = new Uniscribe.SCRIPT_FONTPROPERTIES();
            sfp.cBytes = Marshal.SizeOf(typeof(Uniscribe.SCRIPT_FONTPROPERTIES));

            for (int i = 0; i < 2; i++)
            {
                try
                {
                    res = 0;
                    res = Uniscribe.ScriptGetFontProperties(HDC, ref psc, ref sfp);

                    if (res != 0)
                    {
                        if (res == Win32.E_PENDING)
                        {
                            throw new ArgumentException();
                        }
                        else
                        {
                            throw new Exception(); // Some kind of error.
                        }
                    }

                    break;
                }
                catch (ArgumentException)
                {
                    // ... select font into hdc ...

                    hdcSrc = Win32.GetDC(IntPtr.Zero);
                    HDC    = Win32.CreateCompatibleDC(hdcSrc);

                    old_font = Win32.SelectObject(HDC, hfont);

                    // Loop again...
                    continue;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    break;
                }
            }

            if (old_font != IntPtr.Zero)
            {
                Win32.SelectObject(HDC, old_font);  // Put back the previous font.
            }
            Win32.ReleaseDC(IntPtr.Zero, HDC);
            Win32.ReleaseDC(IntPtr.Zero, hdcSrc);

            // Need to tell Uniscribe to delete the cache we were using. If you are going
            // to keep the HFONT around, you should probably also keep the cache.
            //             ScriptFreeCache(psc);

            Win32.DeleteObject(hfont);

            return(res == 0);
        }
Ejemplo n.º 46
0
        /// <summary>
        /// Create the font image using GDI+ functionality.
        /// </summary>
        void CreateGdiFontImage(XFont font, XPdfFontOptions options /*, XPrivateFontCollection privateFontCollection*/)
        {
            System.Drawing.Font gdiFont = font.RealizeGdiFont();
#if DEBUG_
            logFont = new NativeMethods.LOGFONT();
            gdiFont.ToLogFont(logFont);
            Debug.WriteLine("FontData: " + logFont.lfFaceName);
#endif
            this.data = null;

            // PFC
            //if (privateFontCollection != null)
            //{
            //  //XPrivateFont privateFont = privateFontCollection.FindFont(logFont.lfFaceName, logFont.lfWeight >= 700, logFont.lfItalic > 0);
            //  XGlyphTypeface privateFont = privateFontCollection.FindFont(font.Name, font.Bold, font.Italic);
            //  if (privateFont != null)
            //  {
            //    //////int size = privateFont.GetData(ref this.data);
            //    //////if (size > 0)
            //    //////{
            //    //////  this.data = new byte[size];
            //    //////  privateFont.GetData(ref this.data, size);
            //    //////}
            //  }
            //}
            if (this.data == null)
            {
                var assembly = FontDataConfig.ResourceAssembly;
                var name     = string.Format("{0}.FontHacks.{1}{2}{3}.fontdat",
                                             assembly != null ? assembly.GetName().Name : string.Empty,
                                             font.Name,
                                             font.Bold ? ".Bold" : string.Empty,
                                             font.Italic ? ".Italic" : string.Empty);
                if (assembly != null && new List <string>(assembly.GetManifestResourceNames()).Contains(name))
                {
                    System.Diagnostics.Debug.WriteLine("*** Reading fontdata from Resource");
                    using (var s = assembly.GetManifestResourceStream(name))
                    {
                        this.data = new byte[s.Length];
                        s.Read(this.data, 0, (int)s.Length);
                    }
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("*** Reading fontdata from GDI+");
                    int    error;
                    IntPtr hfont = gdiFont.ToHfont();
                    using (var dcBmp = new Bitmap(100, 100))
                        using (var dc = Graphics.FromImage(dcBmp))
                        {
                            IntPtr hdc = dc.GetHdc();
                            error = Marshal.GetLastWin32Error();
                            IntPtr oldFont = NativeMethods.SelectObject(hdc, hfont);
                            error = Marshal.GetLastWin32Error();
                            // size is exactly the size of the font file.
                            int size = NativeMethods.GetFontData(hdc, 0, 0, null, 0);
                            error = Marshal.GetLastWin32Error();
                            if (size > 0)
                            {
                                this.data = new byte[size];
                                int effectiveSize = NativeMethods.GetFontData(hdc, 0, 0, this.data, this.data.Length);
                                Debug.Assert(size == effectiveSize);
                                if (FontDataConfig.SaveFont)
                                {
                                    FileExtensions.WriteFileBytes(this.data, string.Format("..\\..\\FontHacks\\{0}{1}{2}.fontdat",
                                                                                           font.Name,
                                                                                           font.Bold ? ".Bold" : string.Empty,
                                                                                           font.Italic ? ".Italic" : string.Empty));
                                }
                                NativeMethods.SelectObject(hdc, oldFont);
                                NativeMethods.ReleaseDC(IntPtr.Zero, hdc);
                                error.GetType();
                            }
                            else
                            {
                                // Sometimes size is -1 (GDI_ERROR), but I cannot determine why. It happens only with the font 'Symbol'.
                                // The issue occurs the first time in early 2005, when I start writing PDFsharp. I could not fix it and after
                                // some code refactoring the problem disappears.
                                // There was never a report from anyone about this issue.
                                // Now I get it again (while debugging QBX 2006). Maybe it is a problem with my PC at my home office.
                                // As a work-around I create a new font handle with a different height value. This works. Maybe the
                                // font file gets locked somewhere. Very very strange.

                                // IF SOMEONE ELSE COMES HERE PLEASE LET ME KNOW!

                                // Clean up old handles
                                NativeMethods.SelectObject(hdc, oldFont);
                                NativeMethods.ReleaseDC(IntPtr.Zero, hdc);

                                // Try again with new font handle
                                var logFont = new NativeMethods.LOGFONT();
                                gdiFont.ToLogFont(logFont);
                                logFont.lfHeight += 1; // force new handle
                                IntPtr hfont2 = NativeMethods.CreateFontIndirect(logFont);
                                hdc     = NativeMethods.GetDC(IntPtr.Zero);
                                error   = Marshal.GetLastWin32Error();
                                oldFont = NativeMethods.SelectObject(hdc, hfont2);
                                error   = Marshal.GetLastWin32Error();
                                // size is exactly the size of the font file.
                                size  = NativeMethods.GetFontData(hdc, 0, 0, null, 0);
                                error = Marshal.GetLastWin32Error();
                                if (size > 0)
                                {
                                    this.data = new byte[size];
                                    int effectiveSize = NativeMethods.GetFontData(hdc, 0, 0, this.data, this.data.Length);
                                    Debug.Assert(size == effectiveSize);
                                }
                                NativeMethods.SelectObject(hdc, oldFont);
                                NativeMethods.ReleaseDC(IntPtr.Zero, hdc);
                                NativeMethods.DeleteObject(hfont2);
                                error.GetType();
                            }
                        }
                }
                if (this.data == null)
                {
                    throw new InvalidOperationException("Internal error. Font data could not retrieved.");
                }
            }
        }
Ejemplo n.º 47
0
            protected override void WndProc(ref Message m)
            {
                switch (m.Msg)
                {
                case 0x000F:                        //WM_PAINT
                    if (parent.FullyCustomHeader)
                    {
                        Win32.RECT update = new Win32.RECT();
                        if (Win32.GetUpdateRect(m.HWnd, ref update, false) == 0)
                        {
                            break;
                        }
                        //Fill the paintstruct
                        Win32.PAINTSTRUCT ps  = new Win32.PAINTSTRUCT();
                        IntPtr            hdc = Win32.BeginPaint(m.HWnd, ref ps);
                        //Create graphics object from the hdc
                        Graphics g = Graphics.FromHdc(hdc);
                        //Get the non-item rectangle
                        int        left     = 0;
                        Win32.RECT itemRect = new Win32.RECT();
                        for (int i = 0; i < parent.Columns.Count; i++)
                        {
                            //HDM_GETITEMRECT
                            Win32.SendMessage(m.HWnd, 0x1200 + 7, i, ref itemRect);
                            left += itemRect.right - itemRect.left;
                        }
                        parent.headerHeight = itemRect.bottom - itemRect.top;
                        if (left >= ps.rcPaint.left)
                        {
                            left = ps.rcPaint.left;
                        }

                        Rectangle r = new Rectangle(left, ps.rcPaint.top,
                                                    ps.rcPaint.right - left, ps.rcPaint.bottom - ps.rcPaint.top);
                        Rectangle r1 = new Rectangle(ps.rcPaint.left, ps.rcPaint.top,
                                                     ps.rcPaint.right - left, ps.rcPaint.bottom - ps.rcPaint.top);

                        g.FillRectangle(new SolidBrush(parent.headerBackColor), r);

                        //If we have a valid event handler - call it
                        if (parent.DrawHeader != null && !parent.DefaultCustomDraw)
                        {
                            parent.DrawHeader(new DrawHeaderEventArgs(g, r,
                                                                      itemRect.bottom - itemRect.top));
                        }
                        else
                        {
                            parent.DrawHeaderBorder(new DrawHeaderEventArgs(g, r,
                                                                            itemRect.bottom - itemRect.top));
                        }
                        //Now we have to check if we have owner-draw columns and fill
                        //the DRAWITEMSTRUCT appropriately
                        int counter = 0;
                        foreach (ListColumn mm in parent.Columns)
                        {
                            if (mm.OwnerDraw)
                            {
                                Win32.DRAWITEMSTRUCT dis = new Win32.DRAWITEMSTRUCT();
                                dis.ctrlType   = 100;                                      //ODT_HEADER
                                dis.hwnd       = m.HWnd;
                                dis.hdc        = hdc;
                                dis.itemAction = 0x0001;                                        //ODA_DRAWENTIRE
                                dis.itemID     = counter;
                                //Must find if some item is pressed
                                Win32.HDHITTESTINFO hi = new Win32.HDHITTESTINFO();
                                hi.pt.X = parent.PointToClient(MousePosition).X;
                                hi.pt.Y = parent.PointToClient(MousePosition).Y;
                                int hotItem = Win32.SendMessage(m.HWnd, 0x1200 + 6, 0, ref hi);
                                //If clicked on a divider - we don't have hot item
                                if (hi.flags == 0x0004 || hotItem != counter)
                                {
                                    hotItem = -1;
                                }
                                if (hotItem != -1 && mouseDown)
                                {
                                    dis.itemState = 0x0001;                                            //ODS_SELECTED
                                }
                                else
                                {
                                    dis.itemState = 0x0020;
                                }
                                //HDM_GETITEMRECT
                                Win32.SendMessage(m.HWnd, 0x1200 + 7, counter, ref itemRect);
                                dis.rcItem = itemRect;
                                //Send message WM_DRAWITEM
                                Win32.SendMessage(parent.Handle, 0x002B, 0, ref dis);
                            }
                            counter++;
                        }
                        Win32.EndPaint(m.HWnd, ref ps);
                    }
                    else
                    {
                        base.WndProc(ref m);
                    }
                    break;

                case 0x0014:                        //WM_ERASEBKGND
                    //We don't need to do anything here in order to reduce flicker
                    if (parent.FullyCustomHeader)
                    {
                        break;
                    }
                    else
                    {
                        base.WndProc(ref m);
                    }
                    break;

                case 0x0201:                //WM_LBUTTONDOWN
                    mouseDown = true;
                    base.WndProc(ref m);
                    break;

                case 0x0202:                //WM_LBUTTONUP
                    mouseDown = false;
                    base.WndProc(ref m);
                    break;

                case 0x1200 + 5:              //HDM_LAYOUT
                    base.WndProc(ref m);
                    break;

                case 0x0030:                //WM_SETFONT
                    if (parent.IncreaseHeaderHeight > 0)
                    {
                        System.Drawing.Font f = new System.Drawing.Font(parent.Font.Name,
                                                                        parent.Font.SizeInPoints + parent.IncreaseHeaderHeight);
                        m.WParam = f.ToHfont();
                    }
                    base.WndProc(ref m);
                    break;

                default:
                    base.WndProc(ref m);
                    break;
                }
            }
Ejemplo n.º 48
0
		internal static Size MeasureTextInternal (IDeviceContext dc, string text, Font font, Size proposedSize, TextFormatFlags flags, bool useMeasureString)
		{
			if (!useMeasureString && !XplatUI.RunningOnUnix) {
				// Tell DrawText to calculate size instead of draw
				flags |= (TextFormatFlags)1024;		// DT_CALCRECT

				IntPtr hdc = dc.GetHdc ();

				XplatUIWin32.RECT r = XplatUIWin32.RECT.FromRectangle (new Rectangle (Point.Empty, proposedSize));

				IntPtr prevobj;

				if (font != null) {
					prevobj = SelectObject (hdc, font.ToHfont ());
					Win32DrawText (hdc, text, text.Length, ref r, (int)flags);
					prevobj = SelectObject (hdc, prevobj);
					DeleteObject (prevobj);
				}
				else {
					Win32DrawText (hdc, text, text.Length, ref r, (int)flags);
				}

				dc.ReleaseHdc ();

				// Really, I am just making something up here, which as far as I can tell, MS
				// just makes something up as well.  This will require lots of tweaking to match MS.  :(
				Size retval = r.ToRectangle ().Size;

				if (retval.Width > 0 && (flags & TextFormatFlags.NoPadding) == 0) {
					retval.Width += 6;
					retval.Width += (int)retval.Height / 8;
				}

				return retval;
			}
			else {
			StringFormat sf = FlagsToStringFormat (flags);

				Size retval;
				
				if (dc is Graphics)
					retval = (dc as Graphics).MeasureString (text, font, proposedSize.Width == 0 ? Int32.MaxValue : proposedSize.Width, sf).ToSize ();
				else
					retval = TextRenderer.MeasureString (text, font, proposedSize.Width == 0 ? Int32.MaxValue : proposedSize.Width, sf).ToSize ();

				if (retval.Width > 0 && (flags & TextFormatFlags.NoPadding) == 0)
					retval.Width += 9;

				return retval;
			}
		}
		private static void DrawOnHDC(IntPtr compatHdc, string text, Font font, Padding internalBounds,
			Rectangle bounds, Color color, TextFormatFlags formatFlags, IThemeTextOption[] options) {

			//Create the Font to use
			IntPtr hFont = font.ToHfont();
			Native.GDI.SelectObject(compatHdc, hFont);

			//Get theme renderer
			VisualStyleRenderer renderer = new VisualStyleRenderer(VisualStyleElement.Window.Caption.Active);

			//Prepare options
			NativeMethods.DTTOPTS dttOpts = new NativeMethods.DTTOPTS();
			dttOpts.dwSize = Marshal.SizeOf(dttOpts);
			dttOpts.dwFlags = NativeMethods.DTTOPSFlags.DTT_COMPOSITED | NativeMethods.DTTOPSFlags.DTT_TEXTCOLOR;
			dttOpts.crText = ColorTranslator.ToWin32(color);
			foreach (IThemeTextOption op in options)
				op.Apply(ref dttOpts);

			//Set full bounds with padding
			Native.RECT RECT = new Native.RECT(internalBounds.Left, internalBounds.Top,
				bounds.Width - internalBounds.Right, bounds.Height - internalBounds.Bottom);

			//Draw
			int ret = NativeMethods.DrawThemeTextEx(renderer.Handle, compatHdc, 0, 0, text, -1, (int)formatFlags, ref RECT, ref dttOpts);
			if (ret != 0)
				Marshal.ThrowExceptionForHR(ret);

			//Clean up
			Native.GDI.DeleteObject(hFont);
		}
Ejemplo n.º 50
0
        private TextureBase CreateTextureByWinAPI(PPDDevice device)
        {
            var         metrics  = new WinAPI.GLYPHMETRICS();
            var         tmetrics = new WinAPI.TEXTMETRIC();
            var         matrix   = new WinAPI.MAT2();
            TextureBase texture  = null;

            matrix.eM11.value = 1;
            matrix.eM12.value = 0;
            matrix.eM21.value = 0;
            matrix.eM22.value = 1;
            using (var font = new System.Drawing.Font(FaceName, ActualFontSize))
                using (Graphics g = Graphics.FromHwnd(IntPtr.Zero))
                {
                    var hdc        = g.GetHdc();
                    var prev       = WinAPI.SelectObject(hdc, font.ToHfont());
                    var bufferSize = (int)WinAPI.GetGlyphOutlineW(hdc, Character, (uint)6, out metrics, 0, IntPtr.Zero, ref matrix);
                    var buffer     = Marshal.AllocHGlobal(bufferSize);
                    try
                    {
                        uint ret;
                        if ((ret = WinAPI.GetGlyphOutlineW(hdc, Character, (uint)6, out metrics, (uint)bufferSize, buffer, ref matrix)) > 0 && WinAPI.GetTextMetrics(hdc, ref tmetrics))
                        {
                            int iBmp_w = metrics.gmBlackBoxX + (4 - (metrics.gmBlackBoxX % 4)) % 4;
                            int iBmp_h = metrics.gmBlackBoxY;
                            int iOfs_x = metrics.gmptGlyphOrigin.x, iOfs_y = tmetrics.ascent - metrics.gmptGlyphOrigin.y;
                            width    = metrics.gmCellIncX;
                            height   = tmetrics.height;
                            t_width  = Utility.UpperPowerOfTwo(Math.Max(width, iBmp_w + iOfs_x));
                            t_height = Utility.UpperPowerOfTwo(height);
                            texture  = ((PPDFramework.Texture.DX9.TextureFactory)TextureFactoryManager.Factory).Create(device, t_width, t_height, 1, SharpDX.Direct3D9.Pool.SystemMemory, true);

                            using (var textureData = texture.GetTextureData())
                            {
                                var rec = textureData.DataStream;
                                try
                                {
                                    byte[] data = new byte[bufferSize];
                                    Marshal.Copy(buffer, data, 0, bufferSize);
                                    int offset1 = (iOfs_x + iOfs_y * t_width) * 4;
                                    int offset2 = (iOfs_x + t_width - iOfs_x - iBmp_w) * 4;
                                    WinAPI.ZeroMemory(rec.DataPointer, (uint)rec.Length);
                                    var writedata = new byte[] { (byte)255, (byte)255, (byte)255, (byte)255 };
                                    for (int i = 0; i < iBmp_h; i++)
                                    {
                                        for (int j = 0; j < iBmp_w; j++)
                                        {
                                            var alpha = (byte)((255 * data[j + iBmp_w * i]) / 64);
                                            writedata[0] = writedata[1] = writedata[2] = alpha;
                                            writedata[3] = (byte)alpha;
                                            if (j == 0)
                                            {
                                                if (i == 0)
                                                {
                                                    rec.Seek(offset1, System.IO.SeekOrigin.Current);
                                                }
                                                else
                                                {
                                                    rec.Seek(offset2, System.IO.SeekOrigin.Current);
                                                }
                                            }
                                            rec.Write(writedata, 0, writedata.Length);
                                        }
                                    }
                                }
                                catch
                                {
                                    Console.WriteLine("CharTextureError");
                                }
                            }
                        }
                    }
                    finally
                    {
                        WinAPI.SelectObject(hdc, prev);
                        WinAPI.DeleteObject(prev);
                        g.ReleaseHdc(hdc);
                        Marshal.FreeHGlobal(buffer);
                    }
                }
            return(texture);
        }
Ejemplo n.º 51
0
 public MyFont(System.Drawing.Font f)
 {
     this.myFont = f;
     this.hFont  = f.ToHfont();
 }
Ejemplo n.º 52
0
        private FontData RenderGlyphsCleartype(SysDrawFont internalFont, FontCharSet charSet, bool monospace)
        {
            FontGlyphData[] glyphs = new FontGlyphData[charSet.Chars.Length];
            for (int i = 0; i < glyphs.Length; i++)
            {
                glyphs[i].Glyph = charSet.Chars[i];
            }

            int bodyAscent = 0;
            int baseLine   = 0;
            int descent    = 0;
            int ascent     = 0;

            int cols;
            int rows;

            cols = rows = (int)Math.Ceiling(Math.Sqrt(glyphs.Length));

            IntPtr hFont = internalFont.ToHfont();

            PixelData pixelLayer = new PixelData(
                MathF.RoundToInt(cols * internalFont.Size * 1.2f),
                MathF.RoundToInt(rows * internalFont.Height * 1.2f),
                ColorRgba.TransparentBlack);
            Bitmap measureBm = new Bitmap(1, 1);

            Rect[]      atlas        = new Rect[glyphs.Length];
            PixelData[] glyphBitmaps = new PixelData[glyphs.Length];
            using (Graphics measureGraphics = Graphics.FromImage(measureBm)) {
                IntPtr measureHdc = measureGraphics.GetHdc();

                int x = 1;
                int y = 1;
                for (int i = 0; i < glyphs.Length; ++i)
                {
                    string str     = glyphs[i].Glyph.ToString(CultureInfo.InvariantCulture);
                    bool   isSpace = str == " ";

                    Size charSize;
                    GetTextExtentPoint32(measureHdc, str, str.Length, out charSize);

                    // Rasterize a single glyph for rendering
                    Bitmap bm = new Bitmap(Math.Max(1, charSize.Width), internalFont.Height + 1);
                    using (Graphics glyphGraphics = Graphics.FromImage(bm)) {
                        glyphGraphics.Clear(SystemColors.Window);

                        IntPtr hdc = glyphGraphics.GetHdc();
                        SelectObject(hdc, hFont);
                        SetTextColor(hdc, (0 /*B*/ << 16) | (0 /*G*/ << 8) | 0 /*R*/);
                        TextOut(hdc, 0, 0, str, str.Length);
                        glyphGraphics.ReleaseHdc(hdc);
                    }
                    glyphBitmaps[i] = new PixelData();
                    glyphBitmaps[i].FromBitmap(bm);

                    PixelData glyphTempTypo = glyphBitmaps[i];

                    // Update xy values if it doesn't fit anymore
                    if (x + glyphBitmaps[i].Width + 2 > pixelLayer.Width)
                    {
                        x  = 1;
                        y += internalFont.Height + MathF.Clamp((int)MathF.Ceiling(internalFont.Height * 0.1875f), 3, 10);
                    }

                    // Memorize atlas coordinates & glyph data
                    glyphs[i].Size     = glyphBitmaps[i].Size;
                    glyphs[i].Offset.X = glyphBitmaps[i].Width - glyphTempTypo.Width;
                    glyphs[i].Offset.Y = 0; // TTF fonts are rendered on blocks that are the whole size of the height - so no need for offset
                    if (isSpace)
                    {
                        glyphs[i].Size.X   /= 2;
                        glyphs[i].Offset.X /= 2;
                    }
                    glyphs[i].Advance = glyphs[i].Size.X - glyphs[i].Offset.X;

                    atlas[i].X = x;
                    atlas[i].Y = y;
                    atlas[i].W = glyphBitmaps[i].Width;
                    atlas[i].H = (internalFont.Height + 1);

                    // Draw it onto the font surface
                    glyphBitmaps[i].DrawOnto(pixelLayer, BlendMode.Solid, x, y);

                    x += glyphBitmaps[i].Width + MathF.Clamp((int)MathF.Ceiling(internalFont.Height * 0.125f), 2, 10);
                }

                measureGraphics.ReleaseHdc(measureHdc);
            }

            // ToDo: finally
            DeleteObject(hFont);

            // Monospace offset and advance adjustments
            if (monospace)
            {
                float maxGlyphWidth = 0;
                for (int i = 0; i < glyphs.Length; i++)
                {
                    maxGlyphWidth = Math.Max(maxGlyphWidth, glyphs[i].Size.X);
                }
                for (int i = 0; i < glyphs.Length; ++i)
                {
                    glyphs[i].Offset.X -= (int)Math.Round((maxGlyphWidth - glyphs[i].Size.X) / 2.0f);
                    glyphs[i].Advance   = maxGlyphWidth;
                }
            }

            // Determine Font properties
            {
                float lineSpacing = internalFont.FontFamily.GetLineSpacing(internalFont.Style);
                float emHeight    = internalFont.FontFamily.GetEmHeight(internalFont.Style);
                float cellAscent  = internalFont.FontFamily.GetCellAscent(internalFont.Style);
                float cellDescent = internalFont.FontFamily.GetCellDescent(internalFont.Style);

                ascent      = (int)Math.Round(cellAscent * internalFont.Size / emHeight);
                bodyAscent /= charSet.CharBodyAscentRef.Length;
                baseLine   /= charSet.CharBaseLineRef.Length;
                descent     = (int)Math.Round(((float)descent / charSet.CharDescentRef.Length) - (float)baseLine);
            }

            // Aggregate rendered and generated data into our return value
            FontMetrics metrics = new FontMetrics(
                size: internalFont.SizeInPoints,
                height: (int)internalFont.Height,
                ascent: ascent,
                bodyAscent: bodyAscent,
                descent: descent,
                baseLine: baseLine,
                monospace: monospace);

            // Determine kerning pairs
            FontKerningPair[] kerningPairs = null;
            if (monospace)
            {
                kerningPairs = null;
            }
            else
            {
                kerningPairs = this.GatherKerningPairs(glyphs, metrics, glyphBitmaps);
            }

            return(new FontData(pixelLayer, atlas, glyphs, metrics, kerningPairs));
        }
Ejemplo n.º 53
0
		internal override bool GetFontMetrics(Graphics g, Font font, out int ascent, out int descent) {
			IntPtr		dc;
			IntPtr		prevobj;
			TEXTMETRIC	tm;

			tm = new TEXTMETRIC();

			dc = Win32GetDC (IntPtr.Zero);
			prevobj = Win32SelectObject (dc, font.ToHfont ());
			
			if (Win32GetTextMetrics (dc, ref tm) == false) {
				prevobj = Win32SelectObject (dc, prevobj);
				Win32DeleteObject (prevobj);
				Win32ReleaseDC (IntPtr.Zero, dc);
				ascent = 0;
				descent = 0;
				return false;
			}
			prevobj = Win32SelectObject (dc, prevobj);
			Win32DeleteObject (prevobj);
			Win32ReleaseDC (IntPtr.Zero, dc);

			ascent = tm.tmAscent;
			descent = tm.tmDescent;

			return true;
		}
Ejemplo n.º 54
0
		internal static void DrawTextInternal (IDeviceContext dc, string text, Font font, Rectangle bounds, Color foreColor, Color backColor, TextFormatFlags flags, bool useDrawString)
		{
			if (dc == null)
				throw new ArgumentNullException ("dc");

			if (text == null || text.Length == 0)
				return;

			// We use MS GDI API's unless told not to, or we aren't on Windows
			if (!useDrawString && !XplatUI.RunningOnUnix) {
				if ((flags & TextFormatFlags.VerticalCenter) == TextFormatFlags.VerticalCenter || (flags & TextFormatFlags.Bottom) == TextFormatFlags.Bottom)
					flags |= TextFormatFlags.SingleLine;

				// Calculate the text bounds (there is often padding added)
				Rectangle new_bounds = PadRectangle (bounds, flags);
				new_bounds.Offset ((int)(dc as Graphics).Transform.OffsetX, (int)(dc as Graphics).Transform.OffsetY);

				IntPtr hdc = IntPtr.Zero;
				bool clear_clip_region = false;
				
				// If we need to use the graphics clipping region, add it to our hdc
				if ((flags & TextFormatFlags.PreserveGraphicsClipping) == TextFormatFlags.PreserveGraphicsClipping) {
					Graphics graphics = (Graphics)dc;
					Region clip_region = graphics.Clip;
					
					if (!clip_region.IsInfinite (graphics)) {
						IntPtr hrgn = clip_region.GetHrgn (graphics);
						hdc = dc.GetHdc ();
						SelectClipRgn (hdc, hrgn);
						DeleteObject (hrgn);
						
						clear_clip_region = true;
					}
				}
				
				if (hdc == IntPtr.Zero)
					hdc = dc.GetHdc ();
					
				// Set the fore color
				if (foreColor != Color.Empty)
					SetTextColor (hdc, ColorTranslator.ToWin32 (foreColor));

				// Set the back color
				if (backColor != Color.Transparent && backColor != Color.Empty) {
					SetBkMode (hdc, 2);	//1-Transparent, 2-Opaque
					SetBkColor (hdc, ColorTranslator.ToWin32 (backColor));
				}
				else {
					SetBkMode (hdc, 1);	//1-Transparent, 2-Opaque
				}

				XplatUIWin32.RECT r = XplatUIWin32.RECT.FromRectangle (new_bounds);

				IntPtr prevobj;

				if (font != null) {
					prevobj = SelectObject (hdc, font.ToHfont ());
					Win32DrawText (hdc, text, text.Length, ref r, (int)flags);
					prevobj = SelectObject (hdc, prevobj);
					DeleteObject (prevobj);
				}
				else {
					Win32DrawText (hdc, text, text.Length, ref r, (int)flags);
				}

				if (clear_clip_region)
					SelectClipRgn (hdc, IntPtr.Zero);

				dc.ReleaseHdc ();
			}
			// Use Graphics.DrawString as a fallback method
			else {
				Graphics g;
				IntPtr hdc = IntPtr.Zero;
				
				if (dc is Graphics)
					g = (Graphics)dc;
				else {
					hdc = dc.GetHdc ();
					g = Graphics.FromHdc (hdc);
				}

				StringFormat sf = FlagsToStringFormat (flags);

				Rectangle new_bounds = PadDrawStringRectangle (bounds, flags);

				g.DrawString (text, font, ThemeEngine.Current.ResPool.GetSolidBrush (foreColor), new_bounds, sf);

				if (!(dc is Graphics)) {
					g.Dispose ();
					dc.ReleaseHdc ();
				}
			}
		}
Ejemplo n.º 55
0
 public Font(System.Drawing.Font manFont)
 {
     _gdiFont = manFont.ToHfont();
 }
Ejemplo n.º 56
0
        public static bool ScriptGetCMap(string str, System.Drawing.Font font, Uniscribe.SCRIPT_FONTPROPERTIES sfp)
        {
            if (font == null)
            {
                return(false);
            }

            uint res = 0;

            // HFONT hfont = initialize your font;
            IntPtr hfont = font.ToHfont();

            IntPtr psc = IntPtr.Zero; // Initialize to NULL, will be filled lazily.

            IntPtr hdcSrc = IntPtr.Zero;
            IntPtr HDC    = IntPtr.Zero; // Don't give it a DC unless we have to.

            // HFONT old_font = NULL;
            IntPtr old_font = IntPtr.Zero;

            ushort[] pwOutGlyphs = new ushort[str.Length];

            for (int max = 1000; max > 0; --max)
            {
                try
                {
                    res = 0;
                    res = Uniscribe.ScriptGetCMap(HDC, ref psc, str, str.Length, 0, pwOutGlyphs);

                    if (res != 0)
                    {
                        // Different types of failure...
                        if (res == Win32.E_PENDING)
                        {
                            // Need to select the font for the call. Don't do this if we don't have to
                            // since it may be slow.
                            throw new ArgumentException();
                        }
                        if (res == Win32.E_HANDLE)
                        {
                            // The font or the operating system does not support glyph indexes.
                            throw new Exception();
                        }
                        else if (res == Win32.S_FALSE)
                        {
                            // Some of the Unicode code points were mapped to the default glyph.
                            throw new Exception();
                        }
                    }

                    // call ScriptGetFontProperties
                    int defaultGlyph = sfp.wgDefault;

                    for (int i = 0; i < str.Length; i++)
                    {
                        if (pwOutGlyphs[i] == defaultGlyph)
                        {
                            //  character with that index is not available in selected font
                        }
                    }

                    break;
                }
                catch (ArgumentException)
                {
                    // ... select font into hdc ...

                    hdcSrc = Win32.GetDC(IntPtr.Zero);
                    HDC    = Win32.CreateCompatibleDC(hdcSrc);

                    old_font = Win32.SelectObject(HDC, hfont);

                    // Loop again...
                    continue;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    break;
                }
            }

            if (old_font != IntPtr.Zero)
            {
                Win32.SelectObject(HDC, old_font);  // Put back the previous font.
            }
            Win32.ReleaseDC(IntPtr.Zero, HDC);
            Win32.ReleaseDC(IntPtr.Zero, hdcSrc);

            // Need to tell Uniscribe to delete the cache we were using. If you are going
            // to keep the HFONT around, you should probably also keep the cache.
            //             ScriptFreeCache(psc);

            Win32.DeleteObject(hfont);

            return(res == 0);
        }
Ejemplo n.º 57
0
 private List <NameRecord> GetFontNames(System.Drawing.Font font)
 {
     return(GetFontNames(font.ToHfont()));
 }