public virtual IFontMetrics GetMetrics(CMapEncoding?encoding, TypeMeasureOptions options)
        {
            if (!encoding.HasValue)
            {
                encoding = CMapEncoding.WindowsUnicode;
            }

            return(TTFStringMeasurer.Create(this, encoding.Value, options));
        }
        private TTFStringMeasurer(int unitsPerEm, CMAPSubTable offsets, OS2Table oS2, HorizontalHeader hheader, List <HMetric> metrics, TrueTypeFile font, CMapEncoding encoding, TypeMeasureOptions options)
        {
            this._unitsPerEm  = unitsPerEm;
            this._offsets     = offsets;
            this._os2         = oS2;
            this._metrics     = metrics;
            this._lookup      = new Dictionary <char, HMetric>();
            this._options     = options;
            this._fontUseTypo = (oS2.Version >= OS2TableVersion.OpenType15) && ((oS2.Selection & FontSelection.UseTypographicSizes) > 0);

            this._hheader      = hheader;
            this._fontfile     = font;
            this._cMapEncoding = encoding;
        }
示例#3
0
        private async static Task MeasureStringFor(FontDownload loader, string path)
        {
            byte[] data = null;

            data = await loader.LoadFrom(path);


#if UseOpenFont
            ZlibDecompressStreamFunc zipfunc = (byte[] dataIn, byte[] output) =>
            {
                using (var streamIn = new MemoryStream(dataIn))
                {
#if NET6_0
                    ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream input = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream(streamIn);

                    using (var streamOut = new MemoryStream(output))
                        input.CopyTo(streamOut);
#endif
                    return(true);
                }
            };
            WoffDefaultZlibDecompressFunc.DecompressHandler = zipfunc;

            BrotliDecompressStreamFunc brotlifunc = (byte[] dataIn, Stream dataOut) =>
            {
                using (var streamIn = new MemoryStream(dataIn))
                {
                    System.IO.Compression.BrotliStream deflate = new System.IO.Compression.BrotliStream(streamIn, System.IO.Compression.CompressionMode.Decompress);

                    deflate.CopyTo(dataOut);

                    return(true);
                }
            };
            Woff2DefaultBrotliDecompressFunc.DecompressHandler = brotlifunc;


            using (var ms = new System.IO.MemoryStream(data))
            {
                var reader  = new Typography.OpenFont.OpenFontReader();
                var preview = reader.ReadPreview(ms);

                Console.WriteLine("Loaded font reference " + preview.Name);
            }

            using (var ms = new System.IO.MemoryStream(data))
            {
                var    reader   = new Typography.OpenFont.OpenFontReader();
                var    full     = reader.Read(ms);
                string text     = "This is the text to measure";
                var    encoding = Scryber.OpenType.SubTables.CMapEncoding.WindowsUnicode;
                int    fitted;
                var    size = full.MeasureString(text, 0, 12, 10000, true, out fitted);


                Console.WriteLine("String Measured to " + size.ToString() + " and fitted " + fitted + " characters out of " + text.Length);
            }
#else
            TypefaceReader tfreader = new TypefaceReader();
            ITypefaceInfo  info;

            using (var ms = new System.IO.MemoryStream(data))
            {
                info = tfreader.ReadTypeface(ms, path);
                if (null == info)
                {
                    ExitClean("Could not read the info from the font file");
                    return;
                }
                else if (info.FontCount == 0)
                {
                    ExitClean("No fonts could be read from the data: " + info.ErrorMessage ?? "Unknown error");
                    return;
                }
                else
                {
                    Console.WriteLine("Read  " + info.FontCount + " typefaces from the font file " + info.Source);
                    foreach (var reference in info.Fonts)
                    {
                        Console.WriteLine("    " + reference.FamilyName + " (weight: " + reference.FontWeight.ToString() + ", width: " + reference.FontWidth + ", restrictions : " + reference.Restrictions + ", selections : " + reference.Selections.ToString() + ")");
                    }
                }
            }
            TypeMeasureOptions options = new TypeMeasureOptions();

            using (var ms = new System.IO.MemoryStream(data))
            {
                foreach (var fref in info.Fonts)
                {
                    Console.WriteLine();

                    ms.Position = 0;
                    var typeface = tfreader.GetFont(ms, info.Source, fref);

                    if (null == typeface || typeface.IsValid == false)
                    {
                        ExitClean("The font " + fref.ToString() + " was not valid");
                        return;
                    }
                    else
                    {
                        Console.WriteLine("Loaded font reference " + typeface.ToString());
                    }

                    var metrics = typeface.GetMetrics(options);

                    if (null != metrics)
                    {
                        var line = metrics.MeasureLine("This is the text to measure", 0, 12.0, 10000, options);
                        Console.WriteLine("Measured the string to " + line.RequiredWidth + ", " + line.RequiredHeight + " points, and fitted " + line.CharsFitted + " chars" + (line.OnWordBoudary ? " breaking on the word boundary." : "."));
                    }
                    else
                    {
                        ExitClean("No metrics were returned for the font " + typeface.ToString());
                        return;
                    }

                    var ttfData = typeface.GetFileData(DataFormat.TTF);
                    if (null == ttfData)
                    {
                        ExitClean("No data was returned in TTF format for the font " + typeface.ToString());
                    }
                    else
                    {
                        Console.WriteLine("TrueType font data was extracted at " + ttfData.Length + " bytes from the original data of " + data.Length);
                    }

                    var name = typeface.FamilyName;
                    if (typeface.FontWeight != WeightClass.Normal)
                    {
                        if (name.IndexOf(typeface.FontWeight.ToString()) < 0)
                        {
                            name += " " + typeface.FontWeight.ToString();
                        }
                    }
                    if ((typeface.Selections & FontSelection.Italic) > 0)
                    {
                        if (name.IndexOf("Italic") < 0)
                        {
                            name += " Italic";
                        }
                    }

                    loader.SaveToLocal("Output", name + ".ttf", ttfData);
                }
            }

#if Legacy
            var ttf = new Scryber.OpenType.TTFFile(data, 0);

            Console.WriteLine("Loaded font file " + ttf.ToString());

            var    encoding = Scryber.OpenType.SubTables.CMapEncoding.WindowsUnicode;
            string text     = "This is the text to measure";
            int    fitted;

            var size = ttf.MeasureString(encoding, text, 0, 12, 1000, true, out fitted);

            Console.WriteLine("String Measured to " + size.ToString() + " and fitted " + fitted + " characters out of " + text.Length);

            //Measure 90 wiout word boundary
            size = ttf.MeasureString(encoding, text, 0, 12, 90, false, out fitted);

            Console.WriteLine("String Measured to " + size.ToString() + " and fitted " + fitted + " characters out of " + text.Length + " to string '" + text.Substring(0, fitted) + "'");

            //Measure 90 with word boundary
            size = ttf.MeasureString(encoding, text, 0, 12, 90, true, out fitted);

            Console.WriteLine("String Measured to " + size.ToString() + " and fitted " + fitted + " characters out of " + text.Length + " to string '" + text.Substring(0, fitted) + "'");
#endif

#if Performance
            var stopWatch = System.Diagnostics.Stopwatch.StartNew();

            MeasureStringMeasurer(ttf);

            stopWatch.Stop();

            Console.WriteLine("To measure 4 different strings " + maxRepeat + " times took " + stopWatch.Elapsed.TotalMilliseconds + "ms");
#endif
#endif
        }
        //
        // methods
        //

        public IFontMetrics GetMetrics(TypeMeasureOptions options)
        {
            return(GetMetrics(CMapEncoding.WindowsUnicode, options));
        }
        public static TTFStringMeasurer Create(TrueTypeFile forfont, CMapEncoding encoding, TypeMeasureOptions options)
        {
            HorizontalMetrics table = forfont.Directories["hmtx"].Table as HorizontalMetrics;
            CMAPTable         cmap  = forfont.Directories["cmap"].Table as CMAPTable;
            OS2Table          os2   = forfont.Directories["OS/2"].Table as OS2Table;
            FontHeader        head  = forfont.Directories["head"].Table as FontHeader;
            HorizontalHeader  hhead = forfont.Directories["hhea"].Table as HorizontalHeader;

            CMAPSubTable map = cmap.GetOffsetTable(encoding);

            if (map == null)
            {
                encoding = CMapEncoding.Unicode_20;
                map      = cmap.GetOffsetTable(CMapEncoding.Unicode_20);
            }

            if (map == null)
            {
                encoding = CMapEncoding.MacRoman;
                map      = cmap.GetOffsetTable(CMapEncoding.MacRoman);
            }



            return(new TTFStringMeasurer(head.UnitsPerEm, map, os2, hhead, table.HMetrics, forfont, encoding, options));
        }
        LineSize IFontMetrics.MeasureLine(string chars, int startOffset, double emSize, double maxWidth, TypeMeasureOptions options)
        {
            int fitted;

            double h     = this.LineHeightFU;
            double units = (double)_unitsPerEm;
            double lineh = (h * emSize) / units;

            if (options.IgnoreStartingWhiteSpace)
            {
                while (char.IsWhiteSpace(chars, startOffset) && chars.Length > startOffset)
                {
                    startOffset++;

                    //Gone past the end of the string so return 0
                    if (startOffset >= chars.Length)
                    {
                        return(new LineSize(0, lineh, 0, startOffset, false));
                    }
                }
            }

            //If we have spacing, we cannot take advantage of caching, so fall back to the main font file measure
            if (options.WordSpacing.HasValue || options.CharacterSpacing.HasValue)
            {
                return(_fontfile.MeasureString(this._cMapEncoding, chars, startOffset, emSize, maxWidth, options.WordSpacing, options.CharacterSpacing.HasValue ? options.CharacterSpacing.Value : TrueTypeFile.NoCharacterSpace, TrueTypeFile.NoHorizontalScale, false, options.BreakOnWordBoundaries, out fitted));
            }
            else
            {
                double required = this.MeasureChars(chars, startOffset, emSize, maxWidth, options.BreakOnWordBoundaries, out fitted);

                return(new LineSize(required, lineh, fitted, startOffset, (fitted < chars.Length) && options.BreakOnWordBoundaries));
            }
        }