public D3D11Renderer(ObservableVideoTrack videoTrack, RendererOptions options)
            : base(videoTrack, options)
        {
            // _factoryDWrite = new DWrite.Factory(DWrite.FactoryType.Shared);

            var device2D = new D2D1.Device(DeviceDXGI, new D2D1.CreationProperties
            {
                DebugLevel    = D2D1.DebugLevel.Warning,
                ThreadingMode = D2D1.ThreadingMode.MultiThreaded,
                Options       = D2D1.DeviceContextOptions.None
            });

            _context2D = new D2D1.DeviceContext(device2D, D2D1.DeviceContextOptions.None);

            // Load the background image
            using (var factoryWic = new WIC.ImagingFactory2())
                using (var decoder = new WIC.JpegBitmapDecoder(factoryWic))
                    using (var inputStream = new WIC.WICStream(factoryWic, "background-small.jpg", NativeFileAccess.Read))
                        using (var formatConverter = new WIC.FormatConverter(factoryWic))
                            using (var bitmapScaler = new WIC.BitmapScaler(factoryWic))
                            {
                                decoder.Initialize(inputStream, WIC.DecodeOptions.CacheOnLoad);
                                formatConverter.Initialize(decoder.GetFrame(0), WIC.PixelFormat.Format32bppPBGRA);
                                bitmapScaler.Initialize(formatConverter, VideoFrameWidth, VideoFrameHeight,
                                                        WIC.BitmapInterpolationMode.Fant);
                                _backgroundBitmap = D2D1.Bitmap1.FromWicBitmap(_context2D, bitmapScaler);
                            }

            // Create render target
            _ballEllipse = new D2D1.Ellipse {
                RadiusX = VideoFrameWidth / 20f, RadiusY = VideoFrameWidth / 20f
            };

            _ballBrush = new D2D1.SolidColorBrush(_context2D, new RawColor4(1f, 1f, 0f, 1f));
        }
Пример #2
0
        public WorldObject(string name, bool ignoreCollisions, Vector2 position, string spriteName, RendererOptions renderOptions = null) : base(name, ignoreCollisions, position, spriteName, renderOptions)
        {
            if (AllObjects == null)
                AllObjects = new List<WorldObject>();

            AllObjects.Add(this);
        }
        public static void DrawText(this IImageProcessingContext context, TextGraphicsOptions op, string?text, Font font, Color color, Rectangle bounds)
        {
            if (string.IsNullOrEmpty(text))
            {
                return;
            }

            op.WrapTextWidth = bounds.Width;

            RendererOptions rOp = new RendererOptions(font);

            rOp.WrappingWidth = bounds.Width;

            bool fits = false;

            while (!fits)
            {
                SizeF size = TextMeasurer.Measure(text, rOp);
                fits = size.Height <= bounds.Height && size.Width <= bounds.Width;

                if (!fits)
                {
                    text = text.Truncate(text.Length - 5);
                }
            }

            context.DrawText(op, text, font, color, new Point(bounds.X, bounds.Y));
        }
Пример #4
0
        public (int, RectangleF) GetAdjustedFont(string graphicString, float containerWidth, float containerHeight, int maxFontSize,
                                                 int minFontSize)
        {
            var sizeRect = new RectangleF();

            for (int adjustedSize = maxFontSize; adjustedSize >= minFontSize; adjustedSize--)
            {
                var testFont      = new Font(_dummyFont, adjustedSize);
                var renderOptions = new RendererOptions(testFont)
                {
                    WrappingWidth = containerWidth
                };

                // Test the string with the new size
                sizeRect = TextMeasurer.MeasureBounds(graphicString, renderOptions);
                float volume = sizeRect.Height * sizeRect.Width;

                if (volume < containerWidth * containerHeight)
                {
                    // Good font, return it
                    return(adjustedSize, sizeRect);
                }
            }

            return(minFontSize, sizeRect);
        }
Пример #5
0
        private static Image <T> RenderImage <T>(this FontAtlas fa, T color) where T : struct, IPixel <T>
        {
            // TODO we need the extra pixels here because ImageSharp renders out of bounds and crashes.
            var img = new Image <T>(Configuration.Default, fa.Width + 2, fa.Height);
            var tgo = new TextGraphicsOptions(true);

            tgo.AntialiasSubpixelDepth = 8;

            for (var i = 0; i < fa.MapCount; i++)
            {
                var gm   = fa[i];
                var font = gm.Font;

                foreach (var gd in gm)
                {
                    // TODO lower level control to render single character? This API sucks balls for FA layout + rendering
                    var charStr = char.ConvertFromUtf32(gd.Character);
                    var pos     = (Vector2)gd.Bounds.TopLeft;
                    var ro      = new RendererOptions(font);
                    TextMeasurer.TryMeasureCharacterBounds(charStr.AsSpan(), ro, out var cbs);
                    var cb = cbs[0];
                    img.Mutate(c => c.DrawText(tgo, charStr, font, color, pos - (Vector2)cb.Bounds.Location));
                }
            }

            return(img);
        }
Пример #6
0
        public static Stream Render(string text, Image <Rgba32> image)
        {
            var words = text.Split(' ');

            var font = Arial.CreateFont(2, FontStyle.Regular);

            var canvasPoint = new PointF(image.Width * 0.125F, image.Height * 0.70F);
            var canvasSize  = new SizeF(image.Width * 0.75F, image.Height * 0.3F);

            font = GetLargestFont(canvasSize, font, text);

            var render = new RendererOptions(font);

            foreach (var line in SplitTextForMaxWidth(canvasSize.Width, font, text))
            {
                var textSize = TextMeasurer.Measure(line, render);
                var point    = new PointF(canvasPoint.X + (canvasSize.Width - textSize.Width) / 2, canvasPoint.Y);
                image.Mutate(cl => cl.DrawText(line, font, Brushes.Solid(Color.WhiteSmoke), Pens.Solid(Color.Black, 1), point));
                canvasPoint.Y += textSize.Height;
            }

            var str = new MemoryStream();

            image.SaveAsJpeg(str);
            str.Seek(0, SeekOrigin.Begin);
            return(str);
        }
Пример #7
0
        private static IEnumerable <string> SplitTextForMaxWidth(float width, Font font, string input)
        {
            var    render      = new RendererOptions(font);
            var    words       = input.Replace("\n", " ").Split(' ');
            string currentLine = null;

            foreach (var word in words)
            {
                if (currentLine == null)
                {
                    currentLine = "";
                }

                if (GetWidth(currentLine + word + " ") > width)
                {
                    yield return(currentLine.Trim());

                    currentLine = word;
                }
                else
                {
                    currentLine += " " + word;
                }
            }

            if (currentLine != null)
            {
                yield return(currentLine);
            }

            float GetWidth(string line)
            {
                return(TextMeasurer.Measure(line, render).Width);
            }
        }
Пример #8
0
        public void ContructorTest_FontWithXandYDpisWithOrigin_WithFallbackFonts()
        {
            Font font = FakeFont.CreateFont("ABC");

            FontFamily[] fontFamilys = new[]
            {
                FakeFont.CreateFont("DEF").Family,
                FakeFont.CreateFont("GHI").Family
            };

            var   origin  = new Vector2(123, 345);
            float dpix    = 123;
            float dpiy    = 456;
            var   options = new RendererOptions(font, dpix, dpiy, origin)
            {
                FallbackFontFamilies = fontFamilys
            };

            Assert.Equal(dpix, options.DpiX);
            Assert.Equal(dpiy, options.DpiY);
            Assert.Equal(fontFamilys, options.FallbackFontFamilies);
            Assert.Equal(font, options.Font);
            Assert.Equal(origin, options.Origin);
            VerifyPropertyDefault(options);
        }
Пример #9
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);
        }
Пример #10
0
        public static void RenderTextProcessor(FontFamily fontFamily, string text, float pointSize = 12, IEnumerable <FontFamily> fallbackFonts = null)
        {
            var textOptions = new TextGraphicsOptionsCopy
            {
                ApplyKerning     = true,
                DpiX             = 96,
                DpiY             = 96,
                RenderColorFonts = true,
            };

            if (fallbackFonts != null)
            {
                textOptions.FallbackFonts.AddRange(fallbackFonts);
            }
            var font          = new Font(fontFamily, pointSize);
            var renderOptions = new RendererOptions(font, textOptions.DpiX, textOptions.DpiY)
            {
                ApplyKerning         = true,
                ColorFontSupport     = ColorFontSupport.MicrosoftColrFormat,
                FallbackFontFamilies = textOptions.FallbackFonts?.ToArray()
            };

            var textSize = TextMeasurer.Measure(text, renderOptions);

            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 DrawTextProcessorCopy(textOptions, text, font, new SolidBrushCopy(Color.Black), null, new PointF(5, 5))));

                string fullPath = CreatePath(font.Name, text + ".caching.png");
                Directory.CreateDirectory(System.IO.Path.GetDirectoryName(fullPath));
                img.Save(fullPath);
            }
        }
Пример #11
0
        /// <summary>
        /// Draws the text using the default resolution of <value>72dpi</value> onto the the image filled via the brush then outlined via the pen.
        /// </summary>
        /// <typeparam name="TPixel">The type of the color.</typeparam>
        /// <param name="source">The image this method extends.</param>
        /// <param name="text">The text.</param>
        /// <param name="font">The font.</param>
        /// <param name="brush">The brush.</param>
        /// <param name="pen">The pen.</param>
        /// <param name="location">The location.</param>
        /// <param name="options">The options.</param>
        /// <returns>
        /// The <see cref="Image{TPixel}" />.
        /// </returns>
        public static IImageProcessingContext <TPixel> DrawText <TPixel>(this IImageProcessingContext <TPixel> source, string text, Font font, IBrush <TPixel> brush, IPen <TPixel> pen, PointF location, TextGraphicsOptions options)
            where TPixel : struct, IPixel <TPixel>
        {
            float dpiX = DefaultTextDpi;
            float dpiY = DefaultTextDpi;

            var style = new RendererOptions(font, dpiX, dpiY, location)
            {
                ApplyKerning        = options.ApplyKerning,
                TabWidth            = options.TabWidth,
                WrappingWidth       = options.WrapTextWidth,
                HorizontalAlignment = options.HorizontalAlignment,
                VerticalAlignment   = options.VerticalAlignment
            };

            IPathCollection glyphs = TextBuilder.GenerateGlyphs(text, style);

            var pathOptions = (GraphicsOptions)options;

            if (brush != null)
            {
                source.Fill(brush, glyphs, pathOptions);
            }

            if (pen != null)
            {
                source.Draw(pen, glyphs, pathOptions);
            }

            return(source);
        }
        protected override void BeforeImageApply()
        {
            base.BeforeImageApply();

            // do everything at the image level as we are delegating the processing down to other processors
            var style = new RendererOptions(this.Font, this.Options.DpiX, this.Options.DpiY, this.Location)
            {
                ApplyKerning         = this.Options.ApplyKerning,
                TabWidth             = this.Options.TabWidth,
                WrappingWidth        = this.Options.WrapTextWidth,
                HorizontalAlignment  = this.Options.HorizontalAlignment,
                VerticalAlignment    = this.Options.VerticalAlignment,
                FallbackFontFamilies = this.Options.FallbackFonts,
                ColorFontSupport     = this.definition.Options.RenderColorFonts ? ColorFontSupport.MicrosoftColrFormat : ColorFontSupport.None,
            };

            // (this.definition.Options.RenderColorFonts)
            //{
            this.textRenderer = new ColorCachingGlyphRenderer(this.Configuration.MemoryAllocator, this.Text.Length, this.Pen, this.Brush != null);
            // }
            // else
            // {
            //     this.textRenderer = new CachingGlyphRenderer(this.Configuration.MemoryAllocator, this.Text.Length, this.Pen, this.Brush != null);
            // }

            this.textRenderer.Options = (GraphicsOptions)this.Options;
            var renderer = new TextRenderer(this.textRenderer);

            renderer.RenderText(this.Text, style);
        }
Пример #13
0
        static void Main(string[] args)
        {
            var src_path       = args[0];
            var scr_path_1080p = args[1];
            var slug           = args[2];
            var episode_no     = args[3];
            var subject        = args[4];

            System.IO.Directory.CreateDirectory(OUTPUT_DIR);


            var text = "Episode #" + episode_no + " " + '\u00B7' + " " + subject;

            // create standard cover
            var font            = SystemFonts.CreateFont("Consolas", 100, FontStyle.Regular);
            var rendererOptions = new RendererOptions(font);
            var image           = Image.Load(src_path);

            image.Mutate(ctx => ctx.DrawText(text, font, Rgba32.Black, new PointF(100, 2700)));
            image.Save(OUTPUT_DIR + "/" + slug + ".png");

            // create 1080p cover
            var font_1080p            = SystemFonts.CreateFont("Consolas", 50, FontStyle.Regular);
            var rendererOptions_1080p = new RendererOptions(font_1080p);
            var image_1080p           = Image.Load(scr_path_1080p);

            image_1080p.Mutate(ctx => ctx.DrawText(text, font_1080p, Rgba32.Black, new PointF(350, 970)));
            image_1080p.Save(OUTPUT_DIR + "/" + slug + "_1080p.png");
        }
Пример #14
0
        public static RectangleF MeasureText(string text, Font fnt)
        {
            RendererOptions rendererOptions = new RendererOptions(fnt);
            IPathCollection paths           = TextBuilder.GenerateGlyphs(text, rendererOptions);

            return(paths.Bounds);
        }
        private static void ProcessTapes(IReadOnlyList <ColorTape> colorTapes, string name, Font font)
        {
            Image <Rgb24>   img = new Image <Rgb24>(1920, 1080);
            RendererOptions ro  = new RendererOptions(font);

            img.Mutate(x => {
                PointF pos = new PointF(0, 0);
                foreach (var tape in colorTapes)
                {
                    string[] lines = tape.Chunk.Split('\n');

                    for (int i = 0; i < lines.Length; i++)
                    {
                        string text  = lines[i];
                        var textSize = TextMeasurer.Measure(text, ro);
                        x.DrawText(text, font, Cc2rgb(tape.ForeColor), pos);
                        pos.X += textSize.Width;
                        if (i < lines.Length - 1)
                        {
                            pos.X  = 0;
                            pos.Y += textSize.Height;
                        }
                    }
                }
                x.Contrast(2);
            });

            img.SaveAsPng(RESULT_PATH + name);
        }
Пример #16
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);
        }
Пример #17
0
        /// <summary>
        /// Measures the placement of each character in a rendered string of text.
        /// </summary>
        public static GlyphMetric[] MeasureCharacters(string text, Font font, PointF location)
        {
            var rendererOptions = new RendererOptions(font, location);

            TextMeasurer.TryMeasureCharacterBounds(text, rendererOptions, out var characterBounds);
            //font.Instance.
            return(characterBounds);
        }
Пример #18
0
 private static void VerifyPropertyDefault(RendererOptions options)
 {
     Assert.Equal(4, options.TabWidth);
     Assert.True(options.ApplyKerning);
     Assert.Equal(-1, options.WrappingWidth);
     Assert.Equal(HorizontalAlignment.Left, options.HorizontalAlignment);
     Assert.Equal(VerticalAlignment.Top, options.VerticalAlignment);
 }
        public static string TruncateSubject(string subject, int maxWidth, RendererOptions rendererOptions)
        {
            var fontRectangle = TextMeasurer.Measure(subject, rendererOptions);

            if (fontRectangle.Width > maxWidth)
            {
                do
                {
                    subject       = subject[0..^ 1];
Пример #20
0
        private static void DrawText(string text)
        {
            var fam    = SixLabors.Fonts.SystemFonts.Find("Arial");
            var font   = new Font(fam, 30);
            var style  = new RendererOptions(font, 72);
            var glyphs = SixLabors.Shapes.TextBuilder.GenerateGlyphs(text, style);

            glyphs.SaveImage("Text", text + ".png");
        }
Пример #21
0
        /// <summary>
        /// Generates the shapes corresponding the glyphs described by the font and with the settings withing the FontSpan
        /// </summary>
        /// <param name="text">The text to generate glyphs for</param>
        /// <param name="location">The location</param>
        /// <param name="style">The style and settings to use while rendering the glyphs</param>
        /// <returns>The <see cref="IPathCollection"/></returns>
        public static IPathCollection GenerateGlyphs(string text, PointF location, RendererOptions style)
        {
            var glyphBuilder = new GlyphBuilder(location);

            var renderer = new TextRenderer(glyphBuilder);

            renderer.RenderText(text, style);

            return(glyphBuilder.Paths);
        }
Пример #22
0
        /// <summary>
        /// Generates the shapes corresponding the glyphs described by the font and with the setting in within the FontSpan along the described path.
        /// </summary>
        /// <param name="text">The text to generate glyphs for</param>
        /// <param name="path">The path to draw the text in relation to</param>
        /// <param name="style">The style and settings to use while rendering the glyphs</param>
        /// <returns></returns>
        public static IPathCollection GenerateGlyphs(string text, IPath path, RendererOptions style)
        {
            var glyphBuilder = new PathGlyphBuilder(path);

            var renderer = new TextRenderer(glyphBuilder);

            renderer.RenderText(text, style);

            return(glyphBuilder.Paths);
        }
Пример #23
0
        public void DrawProgressBar(int percentage, int width, FontSize fontSize = FontSize.Medium, int borderThickness = 2, int cornerRadius = 16, int padding = 4)
        {
            // Clamp percentage to the [0;100] range
            var percents = percentage < 0 ? 0 : (percentage > 100 ? 100 : percentage);
            var text     = $"{percents}%";

            var font = fonts[fontSize];

#if IMAGESHARP_V2
            var options = new TextOptions(font);
#else
            var options = new RendererOptions(font);
#endif

            // In order for the text to feel correctly vertically centered, we measure a string with characters
            // that go below (like g or j) and others that go up (like t or f). We say this should be the text height.
            var textHeight          = TextMeasurer.Measure("gf", options).Height;
            var textWidth           = TextMeasurer.Measure(text, options).Width;
            var textSizeWithPadding = new SizeF(textWidth + padding, textHeight + padding);

            var rectangleSize = new SizeF(
                width >= textSizeWithPadding.Width ? width : textSizeWithPadding.Width,
                textSizeWithPadding.Height);

            var color           = palette[percents];
            var borderRectangle = Align(rectangleSize, HorizontalAlignment.Center, VerticalAlignment.Center, 0);

            if (cornerRadius <= 0) // No rounded corners
            {
                var valueWidth     = borderRectangle.Width * (percents / 100f);
                var valueRectangle = new RectangularPolygon(
                    borderRectangle.Left, borderRectangle.Top,
                    valueWidth, borderRectangle.Height);

                _ = Context.Fill(color.WithAlpha(0.33f), valueRectangle);
                _ = Context.Draw(Pens.Solid(color, borderThickness), borderRectangle);
            }
            else
            {
                var invertedValueWidth     = borderRectangle.Width * (1f - percents / 100f);
                var invertedValueRectangle = new RectangularPolygon(
                    borderRectangle.Right - invertedValueWidth, borderRectangle.Top,
                    invertedValueWidth, borderRectangle.Height);

                var contour = borderRectangle.ToRoundedRectangle(cornerRadius);
                var clippedValueRectangle = contour.Clip(invertedValueRectangle);

                _ = Context.Fill(color.WithAlpha(0.33f), clippedValueRectangle);
                _ = Context.Draw(Pens.Solid(color, borderThickness), contour);
            }

            // Draw the text
            var alignedText = Align(textWidth, textHeight, HorizontalAlignment.Center, VerticalAlignment.Center, 0);
            _ = Context.DrawText(text, font, Color.White, new PointF(alignedText.X, alignedText.Y));
        }
Пример #24
0
        public static void RenderText(RendererOptions font, string text)
        {
            GlyphBuilder builder  = new GlyphBuilder();
            TextRenderer renderer = new TextRenderer(builder);

            Primitives.SizeF 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");
        }
Пример #25
0
        public override void VisitTextElement(SvgTextElement element)
        {
            base.VisitTextElement(element);

            var        fonts  = SystemFonts.Collection;
            FontFamily family = null;

            foreach (var f in element.Style.FontFamily.Value)
            {
                var fontName = f;
                if (fontName.Equals("sans-serif"))
                {
                    fontName = DefaultSansSerifFont;
                }
                else if (fontName.Equals("serif"))
                {
                    fontName = DefaultSerifFont;
                }

                if (fonts.TryFind(fontName, out family))
                {
                    break;
                }
            }

            if (ReferenceEquals(family, null)) //FontFamily overrides == operator and can't handle 'null' value on the left.
            {
                family = fonts.Find(DefaultFont);
            }

            var fontSize = element.Style.FontSize.Value.Value;
            var origin   = new PointF(element.X?.Value ?? 0, element.Y?.Value ?? 0);
            var font     = family.CreateFont(fontSize);

            var visitor = new SvgTextSpanTextVisitor();

            element.Accept(visitor);
            var text = visitor.Text;

            // offset by the ascender to account for fonts render origin of top left
            var ascender = ((font.Ascender * font.Size) / (font.EmSize * 72)) * 72;

            var render = new RendererOptions(font, 72, origin - new PointF(0, ascender))
            {
                HorizontalAlignment = element.Style.TextAnchor.Value.AsHorizontalAlignment()
            };

            var glyphs = TextBuilder.GenerateGlyphs(text, render);

            foreach (var p in glyphs)
            {
                this.RenderShapeToCanvas(element, p);
            }
        }
Пример #26
0
        public void ContructorTest_FontOnly()
        {
            var font    = FakeFont.CreateFont("ABC");
            var options = new RendererOptions(font);

            Assert.Equal(72, options.DpiX);
            Assert.Equal(72, options.DpiY);
            Assert.Empty(options.FallbackFontFamilies);
            Assert.Equal(font, options.Font);
            Assert.Equal(Vector2.Zero, options.Origin);
            VerifyPropertyDefault(options);
        }
Пример #27
0
        public static Image <Rgba32> RenderImage(RendererOptions font, string text, Rgba32 backColour, Rgba32 textColour)
        {
            var builder  = new GlyphBuilder();
            var renderer = new TextRenderer(builder);
            var size     = TextMeasurer.Measure(text, font);

            renderer.RenderText(text, font);

            builder.Paths
            .SaveImage((int)size.Width, (int)size.Height, out var ret, backColour, textColour);
            return(ret);
        }
Пример #28
0
        public static void RenderText(RendererOptions font, string text)
        {
            var           builder  = new GlyphBuilder();
            var           renderer = new TextRenderer(builder);
            FontRectangle size     = TextMeasurer.Measure(text, font);

            font.ColorFontSupport = ColorFontSupport.MicrosoftColrFormat;
            renderer.RenderText(text, font);

            builder.Paths
            .SaveImage(builder.PathColors, (int)size.Width + 20, (int)size.Height + 20, font.Font.Name, text + ".png");
        }
Пример #29
0
        public void ContructorTest_FontWithSingleDpi()
        {
            var   font    = FakeFont.CreateFont("ABC");
            float dpi     = 123;
            var   options = new RendererOptions(font, dpi);

            Assert.Equal(dpi, options.DpiX);
            Assert.Equal(dpi, options.DpiY);
            Assert.Empty(options.FallbackFontFamilies);
            Assert.Equal(font, options.Font);
            Assert.Equal(Vector2.Zero, options.Origin);
            VerifyPropertyDefault(options);
        }
Пример #30
0
        public void ContructorTest_FontWithOrigin()
        {
            Font font    = FakeFont.CreateFont("ABC");
            var  origin  = new Vector2(123, 345);
            var  options = new RendererOptions(font, origin);

            Assert.Equal(72, options.DpiX);
            Assert.Equal(72, options.DpiY);
            Assert.Empty(options.FallbackFontFamilies);
            Assert.Equal(font, options.Font);
            Assert.Equal(origin, options.Origin);
            VerifyPropertyDefault(options);
        }
Пример #31
0
        public MemoryStream SpoilerTxt(string spoil)
        {
            var             fill  = Brushes.Solid <Rgba32>(Rgba32.Black);
            var             brush = Brushes.Solid <Rgba32>(Rgba32.White);
            RendererOptions op    = new RendererOptions(_Spoiltxt);
            var             text  = WordWrap(spoil, 120);
            var             tsize = TextMeasurer.MeasureBounds(text, op);

            int[] size = { Convert.ToInt32(tsize.Width) + 20, Convert.ToInt32(tsize.Height) + 20 };
            var   img2 = new Image <Rgba32>(size[0], size[1]);

            img2.DrawText(text, _Spoiltxt, brush, new PointF(0, 0), new TextGraphicsOptions(true));
            img2.BackgroundColor(Rgba32.Black);
            var img1 = new Image <Rgba32>(img2.Width, img2.Height);

            _Spoil = _fonts.Find("Whitney-Bold").CreateFont(img2.Width * 0.064f);
            var rect = new Rectangle(0, 0, img2.Width, img2.Height);

            img1.BackgroundColor(Rgba32.Black, rect);
            img1.DrawText("Spoiler Warning" + "\r\n" + "(Mouse over to view)", _Spoil, brush, new PointF(0, 0), new TextGraphicsOptions(true)
            {
                WrapTextWidth = img1.Width - 20
            });
            MagickImage f1 = new MagickImage(img1.ToStream());
            MagickImage f2 = new MagickImage(img2.ToStream());

            MagickImage[] frames = { f1, f2 };
            MemoryStream  ms     = new MemoryStream();

            using (MagickImageCollection gif = new MagickImageCollection())
            {
                gif.Add(f1);
                gif.Add(f2);

                for (int i = 0; i < gif.Count; i++)
                {
                    gif[i].AnimationDelay      = 50;
                    gif[i].AnimationIterations = 1;
                }
                QuantizeSettings settings = new QuantizeSettings
                {
                    Colors       = 256,
                    DitherMethod = DitherMethod.No
                };
                gif.Quantize(settings);
                gif.Optimize();
                gif.Write(ms, MagickFormat.Gif);
                ms.Position = 0;
            }
            return(ms);
        }
Пример #32
0
 public TextObject(Vector2 position, string text, float scale = 1, RendererOptions options = null) : base("TextObject", true, position, "none", options == null? new RendererOptions(Color.Black) : options)
 {
     Text = text;
     Scale = scale;
 }
Пример #33
0
        public GameObject(string name, bool ignoreCollisions, Vector2 position, string spriteName, RendererOptions rendererOptions = null)
        {
            transform = new Transform(this);
            renderer = new Renderer(this);

            int cols = 1;
            int rows = 1;
            int index = 0;

            if (rendererOptions != null)
            {
                renderer.BlendColor = rendererOptions.color;
                cols = rendererOptions.cols;
                rows = rendererOptions.rows;
                index = rendererOptions.index;
            }

            renderer.SetTexture(spriteName, cols, rows);
            renderer.ImageIndex = index;

            this.IgnoreCollisions = ignoreCollisions;

            transform.Position = position;

            if (AllObjects == null)
                AllObjects = new List<GameObject>();

            if (NewObjects == null)
                NewObjects = new List<GameObject>();

            NewObjects.Add(this);

            this.spriteName = spriteName;
            this.Name = name;
        }