Esempio n. 1
0
        public void MeasuringWordWithAccentedCharacterDoesNotThrow(char c)
        {
            FontFamily arial = new FontCollection().Install(TestFonts.OpenSansFile);
            var        font  = new Font(arial, 1f, FontStyle.Regular);

            FontRectangle size = TextMeasurer.Measure($"abc{c}def", new RendererOptions(font, 72));
        }
Esempio n. 2
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                return;
            }


            FontCollection fonts         = new FontCollection();
            var            actionManFont = fonts.Install("/home/peter/Pictures/captai/Action_Man.ttf");
            var            font          = new Font(actionManFont, 39, FontStyle.Regular);

            FontRectangle s = new FontRectangle(369, 80, 506, 302);

            var textGraphicOptions = new TextGraphicsOptions()
            {
                TextOptions =
                {
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment   = VerticalAlignment.Center,
                    WrapTextWidth       = 164.0f
                }
            };

            var result = "output.jpg";

            using (Image <Rgba32> image = (Image <Rgba32>)Image.Load("/home/peter/Pictures/captai/template.png"))
            {
                image.Mutate(x => x
                             .DrawText(textGraphicOptions, args[0], font, Color.Black, new PointF(362.0f, 171.0f))
                             );
                image.Save(result);
            }
        }
Esempio n. 3
0
        public void MeasuringAccentedCharacterDoesNotThrow(char c)
        {
            FontFamily arial = new FontCollection().Add(TestFonts.OpenSansFile);
            var        font  = new Font(arial, 1f, FontStyle.Regular);

            FontRectangle size = TextMeasurer.Measure(c.ToString(), new TextOptions(font));
        }
Esempio n. 4
0
        public Task Initialize(MatrixParams mparams)
        {
            this.sizex = mparams.SizeX;
            this.sizey = mparams.SizeY;
            var size = new Size((int)this.sizex, (int)this.sizey);

            this.pbuf = new RGBPixel[sizex, sizey];

            Font font  = null;
            var  fonts = new FontCollection();

            foreach (var f in fontpfade)
            {
                if (System.IO.File.Exists(f))
                {
                    fonts.Install(f);
                }
            }
            try{
                font = SystemFonts.CreateFont(this.FontFamily, this.Size, this.Style);
            }
            catch (Exception d) {}
            FontRectangle sz     = TextMeasurer.Measure(this.Text, new RendererOptions(font));
            Size          _tsize = new Size(Convert.ToInt32(sz.Width + 1), Convert.ToInt32(sz.Height + 1));

            this._image = new Image <Rgba32>(_tsize.Width, _tsize.Height);
            _image.Mutate(ctx =>
            {
                //ctx.Fill(Rgba32.Black);
                ctx.DrawText(this.Text, font, Brushes.Solid(Color.White), Pens.Solid(Color.Beige, 1), PointF.Empty);
            });

            _tpos = _image.Width / 2;
            return(Task.CompletedTask);
        }
Esempio n. 5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GlyphMetric"/> struct.
 /// </summary>
 /// <param name="codePoint">Unicode codepoint of the character.</param>
 /// <param name="bounds">The bounds.</param>
 /// <param name="isControlCharacter">Whether the character is a control character.</param>
 public GlyphMetric(int codePoint, FontRectangle bounds, bool isControlCharacter)
 {
     this.Codepoint          = codePoint;
     this.Character          = char.ConvertFromUtf32(codePoint);
     this.Bounds             = bounds;
     this.IsControlCharacter = isControlCharacter;
 }
Esempio n. 6
0
 /// <inheritdoc/>
 bool IGlyphRenderer.BeginGlyph(FontRectangle rect, GlyphRendererParameters cachKey)
 {
     this.currentColor = null;
     this.builder.Clear();
     this.glyphBounds.Add(rect);
     return(this.BeginGlyph(rect, cachKey));
 }
Esempio n. 7
0
        public static void RenderTextProcessor(
            FontFamily fontFamily,
            string text,
            float pointSize = 12,
            IEnumerable <FontFamily> fallbackFonts = null)
        {
            Font        font        = new(fontFamily, pointSize);
            TextOptions textOptions = new(font)
            {
                Dpi = 96,
            };

            if (fallbackFonts != null)
            {
                textOptions.FallbackFontFamilies = fallbackFonts.ToArray();
            }

            FontRectangle textSize = TextMeasurer.Measure(text, textOptions);

            textOptions.Origin = new PointF(5, 5);

            using var img = new Image <Rgba32>((int)Math.Ceiling(textSize.Width) + 20, (int)Math.Ceiling(textSize.Height) + 20);
            img.Mutate(x => x.Fill(Color.White).ApplyProcessor(new DrawTextProcessor(x.GetDrawingOptions(), textOptions, text, new SolidBrush(Color.Black), null)));

            string fullPath = CreatePath(font.Name, text + ".caching.png");

            Directory.CreateDirectory(IOPath.GetDirectoryName(fullPath));
            img.Save(fullPath);
        }
Esempio n. 8
0
        public OpenXmlSize MeasureText(IOpenXmlTextStyle defaultTextStyle, IOpenXmlTheme theme, OpenXmlUnit?width)
        {
            // TODO: subtract border
            // TODO: measure each pararaph individually

            int level = 1;
            IOpenXmlParagraphTextStyle defaultParagraphTextStyle = defaultTextStyle.GetParagraphTextStyle(level);

            string        text     = this.GetText();
            string        typeface = theme.ResolveFontTypeface(this.GetFont() ?? defaultParagraphTextStyle.LatinTypeface);
            double        fontSize = this.GetFontSize() ?? defaultParagraphTextStyle.Size ?? 9.0;
            double        kerning  = this.GetKerning() ?? defaultParagraphTextStyle.Kerning ?? 0.0;
            OpenXmlMargin margin   = this.GetTextMargin();

            Font font = SystemFonts.Find(typeface).CreateFont((float)fontSize);

            RendererOptions options = new RendererOptions(font, 72)
            {
                WrappingWidth = width.HasValue ? (float)(width.Value - margin.Left - margin.Right).AsPoints() : -1.0f,
                ApplyKerning  = kerning != 0.0,
                LineSpacing   = 1 / 1.2f
            };

            FontRectangle rect   = TextMeasurer.Measure(text, options);
            OpenXmlSize   result = new OpenXmlSize(
                width.HasValue ? width.Value : (OpenXmlUnit.Points(rect.Width) + margin.Left + margin.Right),
                OpenXmlUnit.Points(rect.Height * 1.2) + margin.Top + margin.Bottom
                );

            return(result);
        }
Esempio n. 9
0
        private static double GetCellWidth(int defaultCharWidth, int colspan,
                                           ICellStyle style, double width, string str, Font windowsFont, ICell cell)
        {
            //Rectangle bounds;
            double        actualWidth;
            FontRectangle sf = TextMeasurer.Measure(str, new TextOptions(windowsFont));

            if (style.Rotation != 0)
            {
                double angle = style.Rotation * 2.0 * Math.PI / 360.0;
                double x1    = Math.Abs(sf.Height * Math.Sin(angle));
                double x2    = Math.Abs(sf.Width * Math.Cos(angle));
                actualWidth = Math.Round(x1 + x2, 0, MidpointRounding.ToEven);
                //bounds = layout.getOutline(trans).getBounds();
            }
            else
            {
                //bounds = layout.getBounds();
                actualWidth = Math.Round(sf.Width, 0, MidpointRounding.ToEven);
            }
            // entireWidth accounts for leading spaces which is excluded from bounds.getWidth()
            //double frameWidth = bounds.getX() + bounds.getWidth();
            //width = Math.max(width, ((frameWidth / colspan) / defaultCharWidth) + style.getIndention());
            width = Math.Max(width, (actualWidth / colspan / defaultCharWidth) + cell.CellStyle.Indention);
            return(width);
        }
Esempio n. 10
0
        public void VerticalAlignmentTests(
            VerticalAlignment vertical,
            HorizontalAlignment horizental,
            float top, float left)
        {
            string text = "hello world\nhello";
            Font   font = CreateFont(text);

            int scaleFactor = 72 * font.EmSize; // 72 * emSize means 1 point = 1px
            var span        = new RendererOptions(font, scaleFactor)
            {
                HorizontalAlignment = horizental,
                VerticalAlignment   = vertical
            };

            IReadOnlyList <GlyphLayout> glyphsToRender = new TextLayout().GenerateLayout(text.AsSpan(), span);
            IFontInstance fontInst   = span.Font.Instance;
            float         lineHeight = (fontInst.LineHeight * span.Font.Size) / (fontInst.EmSize * 72);

            lineHeight *= scaleFactor;
            FontRectangle bound = TextMeasurer.GetBounds(glyphsToRender, new Vector2(span.DpiX, span.DpiY));

            Assert.Equal(310, bound.Width, 3);
            Assert.Equal(40, bound.Height, 3);
            Assert.Equal(left, bound.Left, 3);
            Assert.Equal(top, bound.Top, 3);
        }
        private static IImageProcessingContext ApplyScalingWaterMarkSimple(IImageProcessingContext processingContext,
                                                                           Font font,
                                                                           string text,
                                                                           Color color,
                                                                           float padding)
        {
            Size imgSize = processingContext.GetCurrentSize();

            float targetWidth  = imgSize.Width - (padding * 2);
            float targetHeight = imgSize.Height - (padding * 2);

            // measure the text size
            FontRectangle size = TextMeasurer.Measure(text, new RendererOptions(font));

            //find out how much we need to scale the text to fill the space (up or down)
            float scalingFactor = Math.Min(imgSize.Width / size.Width, imgSize.Height / size.Height);

            //create a new font
            Font scaledFont = new Font(font, scalingFactor * font.Size);

            var center             = new PointF(imgSize.Width / 2, imgSize.Height / 2);
            var textGraphicOptions = new TextGraphicsOptions()
            {
                TextOptions =
                {
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment   = VerticalAlignment.Center
                }
            };

            return(processingContext.DrawText(textGraphicOptions, text, scaledFont, color, center));
        }
Esempio n. 12
0
        public void WhiteSpaceAtStartOfLineNotMeasured(string text, float width, float height)
        {
            Font          font = CreateFont(text);
            FontRectangle size = TextMeasurer.MeasureBounds(text, new RendererOptions(font, 72 * font.EmSize));

            Assert.Equal(height, size.Height, 2);
            Assert.Equal(width, size.Width, 2);
        }
Esempio n. 13
0
        protected override Image <Rgba32> Run()
        {
            TimeSpan countDownSpan = timeSpan - stopwatch.Elapsed;
            string   displayText;

            Color      color = Color.White;
            FontFamily fo;

            SystemFonts.TryFind("Times New Roman", out fo);
            Font font = new Font(fo, 20, FontStyle.Regular);

            if (countDownSpan.TotalSeconds > 11)
            {
                font = new Font(fo, 20, FontStyle.Regular);
                string hours   = string.Empty;
                string minutes = string.Empty;
                string seconds = string.Empty;

                if (countDownSpan.Hours > 0)
                {
                    hours = "0" + countDownSpan.Hours.ToString();
                    hours = hours.Substring(hours.Length - 2) + ":";
                }

                minutes = "0" + countDownSpan.Minutes.ToString();
                minutes = minutes.Substring(minutes.Length - 2) + ":";

                seconds = "0" + countDownSpan.Seconds.ToString();
                seconds = seconds.Substring(seconds.Length - 2);

                displayText = hours + minutes + seconds;
            }
            else if (countDownSpan.TotalSeconds <= 1)
            {
                displayText = string.Empty;
            }
            else
            {
                font        = new Font(fo, 35, FontStyle.Regular);
                displayText = countDownSpan.Seconds.ToString();
                color       = color.WithAlpha(LEDEngine3D.Map(countDownSpan.Milliseconds, 1, 1000, 0f, 1f));
            }

            FontRectangle size = TextMeasurer.Measure(
                displayText,
                new RendererOptions(font));

            image = new Image <Rgba32>(LEDWidth, LEDHeight);

            SetBackgroundColor(image);

            image.Mutate(c =>
                         c.DrawText(
                             displayText,
                             font, color, new PointF((image.Width - size.Width) / 2, (image.Height - size.Height) / 2)));

            return(image);
        }
Esempio n. 14
0
        public void TwoTabsAreDoubleWidthOfOneTabMinusXWidth()
        {
            Font          font        = CreateFont("\t x");
            FontRectangle xWidth      = TextMeasurer.MeasureBounds("x", new RendererOptions(font, 72 * font.EmSize));
            FontRectangle tabWidth    = TextMeasurer.MeasureBounds("\tx", new RendererOptions(font, 72 * font.EmSize));
            FontRectangle twoTabWidth = TextMeasurer.MeasureBounds("\t\tx", new RendererOptions(font, 72 * font.EmSize));

            Assert.Equal(twoTabWidth.Width - xWidth.Width, (tabWidth.Width - xWidth.Width) * 2, 2);
        }
Esempio n. 15
0
        public void ThrowsMeasuringWhitespace()
        {
            // wendy one returns wrong points for 'o'
            Font          font = new FontCollection().Add(TestFonts.WendyOneFile).CreateFont(12);
            FontRectangle size = TextMeasurer.MeasureBounds("          ", new TextOptions(new Font(font, 30)));

            Assert.Equal(60, size.Width, 1);
            Assert.Equal(31.6, size.Height, 1);
        }
Esempio n. 16
0
        public void Rendering2TabsAtStartOfLineTooShort()
        {
            Font          font          = CreateFont("\t x");
            FontRectangle xWidth        = TextMeasurer.MeasureBounds("x", new RendererOptions(font, 72 * font.EmSize));
            FontRectangle tabWidth      = TextMeasurer.MeasureBounds("\t\t", new RendererOptions(font, 72 * font.EmSize));
            FontRectangle tabWithXWidth = TextMeasurer.MeasureBounds("\t\tx", new RendererOptions(font, 72 * font.EmSize));

            Assert.Equal(tabWidth.Width + xWidth.Width, tabWithXWidth.Width, 2);
        }
Esempio n. 17
0
        public void MeasureText(string text, float height, float width)
        {
            Font font = CreateFont(text);

            int           scaleFactor = 72 * font.EmSize; // 72 * emSize means 1 point = 1px
            FontRectangle size        = TextMeasurer.MeasureBounds(text, new RendererOptions(font, 72 * font.EmSize));

            Assert.Equal(height, size.Height, 4);
            Assert.Equal(width, size.Width, 4);
        }
        public void CorrectlySetsHeightMetrics()
        {
            // Whitney-book has invalid hhea values.
            Font font = new FontCollection().Add(TestFonts.WhitneyBookFile).CreateFont(25);

            FontRectangle size = TextMeasurer.Measure("H", new TextOptions(font));

            Assert.Equal(17.6, size.Width, 1);
            Assert.Equal(30.6, size.Height, 1);
        }
Esempio n. 19
0
        public void TextWidthFroTabOnlyTextSouldBeSingleTabWidthMultipliedByTabCount(int tabCount)
        {
            Font font = CreateFont("\t x");

            FontRectangle tabWidth      = TextMeasurer.MeasureBounds("\t", new RendererOptions(font, 72 * font.EmSize));
            string        tabString     = string.Empty.PadRight(tabCount, '\t');
            FontRectangle tabCountWidth = TextMeasurer.MeasureBounds(tabString, new RendererOptions(font, 72 * font.EmSize));

            Assert.Equal(tabWidth.Width * tabCount, tabCountWidth.Width, 2);
        }
Esempio n. 20
0
        public void WhiteSpaceAtStartOfLineNotMeasured(string text, float width, float height)
        {
            Font          font = CreateFont(text);
            FontRectangle size = TextMeasurer.MeasureBounds(text, new TextOptions(font)
            {
                Dpi = font.FontMetrics.ScaleFactor
            });

            Assert.Equal(height, size.Height, 2);
            Assert.Equal(width, size.Width, 2);
        }
Esempio n. 21
0
        /// <summary>
        /// Called before any glyphs have been rendered.
        /// </summary>
        /// <param name="bounds">The bounds the text will be rendered at and at whats size.</param>
        void IGlyphRenderer.BeginText(FontRectangle bounds)
        {
            // called before any thing else to provide access to the total required size to redner the text

            _gl.BlendFunc(OpenGL.GL_SRC_ALPHA, OpenGL.GL_ONE_MINUS_SRC_ALPHA);
            _gl.Enable(OpenGL.GL_BLEND);
            _gl.BindTexture(OpenGL.GL_TEXTURE_2D, 0);
            Vector4 colorV = Color;

            _gl.Color(colorV.X, colorV.Y, colorV.Z, colorV.W);
        }
Esempio n. 22
0
        /// <summary>
        /// Begins the glyph.
        /// </summary>
        /// <param name="bounds">The bounds the glyph will be rendered at and at what size.</param>
        /// <param name="paramaters">The set of paramaters that uniquely represents a version of a glyph in at particular font size, font family, font style and DPI.</param>
        /// <returns>Returns true if the glyph should be rendered othersie it returns false.</returns>
        bool IGlyphRenderer.BeginGlyph(FontRectangle bounds, GlyphRendererParameters paramaters)
        {
            // called before each glyph/glyph layer is rendered.
            // The paramaters can be used to detect the exact details
            // of the glyph so that duplicate glyphs could optionally
            // be cached to reduce processing.

            // You can return false to skip all the figures within the glyph (if you return false EndGlyph will still be called)

            return(true);
        }
Esempio n. 23
0
        public static void RenderText(RendererOptions font, string text)
        {
            var           builder  = new GlyphBuilder();
            var           renderer = new TextRenderer(builder);
            FontRectangle size     = TextMeasurer.Measure(text, font);

            renderer.RenderText(text, font);

            builder.Paths
            .SaveImage((int)size.Width + 20, (int)size.Height + 20, font.Font.Name, text + ".png");
        }
Esempio n. 24
0
        public static void RenderText(TextOptions options, string text)
        {
            FontRectangle size = TextMeasurer.Measure(text, options);

            if (size == FontRectangle.Empty)
            {
                return;
            }

            SaveImage(options, text, (int)size.Width, (int)size.Height, options.Font.Name, text + ".png");
        }
Esempio n. 25
0
        public void ThrowsMeasureingWhitespace()
        {
            // wendy one returns wrong points for 'o'
            Font font = new FontCollection().Install(TestFonts.WendyOneFile).CreateFont(12);

            var r = new GlyphRenderer();

            FontRectangle size = TextMeasurer.MeasureBounds("          ", new RendererOptions(new Font(font, 30), 72));

            Assert.Equal(60, size.Width, 1);
            Assert.Equal(31.7, size.Height, 1);
        }
        /// <inheritdoc/>
        protected override void BeginGlyph(FontRectangle rect)
        {
            SegmentInfo point = this.path.PointAlongPath(rect.Left);

            Vector2 targetPoint = point.Point + new PointF(0, rect.Top - this.yOffset);

            // due to how matrix combining works you have to combine thins in the revers order of operation
            // this one rotates the glype then moves it.
            Matrix3x2 matrix = Matrix3x2.CreateTranslation(targetPoint - rect.Location) * Matrix3x2.CreateRotation(point.Angle - Pi, point.Point);

            this.builder.SetTransform(matrix);
        }
Esempio n. 27
0
        public unsafe void MeasureTextWithSpan()
        {
            Font font = CreateFont("hello");

            Span <char> text = stackalloc char[] { 'h', 'e', 'l', 'l', 'o' };

            int scaleFactor = 72 * font.EmSize; // 72 * emSize means 1 point = 1px

            FontRectangle size = TextMeasurer.MeasureBounds(text, new RendererOptions(font, 72 * font.EmSize));

            Assert.Equal(10, size.Height, 4);
            Assert.Equal(130, size.Width, 4);
        }
Esempio n. 28
0
        public void TabWidth0CausesBadTabRendering()
        {
            string        text = "Hello\tworld";
            Font          font = CreateFont(text);
            FontRectangle size = TextMeasurer.MeasureBounds(text, new RendererOptions(font, 72 * font.EmSize)
            {
                TabWidth = 0
            });

            // tab width of 0 should make tabs not render at all
            Assert.Equal(10, size.Height, 4);
            Assert.Equal(280, size.Width, 4);
        }
Esempio n. 29
0
        public void MeasureTextWithKerning(string text, float height, float width, bool enableKerning)
        {
            var  c    = new FontCollection();
            Font font = c.Install(TestFonts.SimpleFontFileData()).CreateFont(12);

            int           scaleFactor = 72 * font.EmSize; // 72 * emSize means 1 point = 1px
            FontRectangle size        = TextMeasurer.MeasureBounds(text, new RendererOptions(new Font(font, 1), 72 * font.EmSize)
            {
                ApplyKerning = enableKerning
            });

            Assert.Equal(height, size.Height, 4);
            Assert.Equal(width, size.Width, 4);
        }
Esempio n. 30
0
        public void TextWidthFroTabOnlyTextSouldBeSingleTabWidthMultipliedByTabCountMinusX(int tabCount)
        {
            Font font = CreateFont("\t x");

            FontRectangle xWidth        = TextMeasurer.MeasureBounds("x", new RendererOptions(font, 72 * font.EmSize));
            FontRectangle tabWidth      = TextMeasurer.MeasureBounds("\tx", new RendererOptions(font, 72 * font.EmSize));
            string        tabString     = "x".PadLeft(tabCount + 1, '\t');
            FontRectangle tabCountWidth = TextMeasurer.MeasureBounds(tabString, new RendererOptions(font, 72 * font.EmSize));

            float singleTabWidth = tabWidth.Width - xWidth.Width;
            float finalTabWidth  = tabCountWidth.Width - xWidth.Width;

            Assert.Equal(singleTabWidth * tabCount, finalTabWidth, 2);
        }