Example #1
0
        public void Evaluate(int SpreadMax)
        {
            if (!this.FFormat.PluginIO.IsConnected)
            {
                this.FOutput.SliceCount = 0;
                return;
            }

            if (this.FFormat.IsChanged || this.FMaxHeight.IsChanged || this.FMaxWidth.IsChanged
                || this.FText.IsChanged || this.FTextAlign.IsChanged || this.FParaAlign.IsChanged)
            {
                //first dispose old outputs
                for (int i = 0; i < this.FOutput.SliceCount; i++)
                {
                    if (this.FOutput[i] != null) { this.FOutput[i].Dispose(); }
                }

                //then set new slicecount
                this.FOutput.SliceCount = SpreadMax;

                //then create new outputs
                for (int i = 0; i < SpreadMax; i++)
                {
                    var tl = new TextLayout(this.dwFactory, this.FText[i], this.FFormat[i], this.FMaxWidth[i], this.FMaxHeight[i]);
                    var align = (int)this.FTextAlign[i];
                    tl.TextAlignment = (TextAlignment)align;
                    tl.ParagraphAlignment = this.FParaAlign[i];
                    this.FOutput[i] = tl;
                }
            }
        }
        protected override void OnCreateDeviceIndependentResources(Direct2DFactory factory)
        {
            base.OnCreateDeviceIndependentResources(factory);

            this._textFormat = DirectWriteFactory.CreateTextFormat("Gabriola",
                FontWeight.Normal,
                FontStyle.Normal,
                FontStretch.Normal,
                72);

            this._textFormat.TextAlignment = TextAlignment.Center;
            this._textFormat.ParagraphAlignment = ParagraphAlignment.Center;

            float width = ClientSize.Width / _dpiScaleX;
            float height = ClientSize.Height / _dpiScaleY;

            this._textLayout = DirectWriteFactory.CreateTextLayout(
                _text,
                this._textFormat,
                width,
                height);

            using (Typography typography = DirectWriteFactory.CreateTypography())
            {
                typography.AddFontFeature(FontFeatureTag.StylisticSet7, 1);
                this._textLayout.SetTypography(typography, new TextRange(0, _text.Length));
            }

            Bitmap bitmap = RenderTarget.CreateBitmap(this.GetType(), "heart.png");

            this._bitmapInlineObject = new BitmapInlineObject(RenderTarget, bitmap);

            this._textLayout.SetInlineObject(this._bitmapInlineObject, new TextRange(2, 1));
        }
Example #3
0
 public void Apply(TextLayout layout)
 {
     if (this.Enabled)
     {
         this.DoApply(layout, this.Range);
     }
 }
Example #4
0
        public void Evaluate(int SpreadMax)
        {
            if (this.FInText.IsChanged || this.FFormat.IsChanged)
            {
                TextFormat format = this.FFormat[0];

                SlimDX.DirectWrite.TextLayout layout = new TextLayout(this.dwFactory, this.FInText[0], format,50000,50000);
                float lastwidth = 0.0f;
                string txt = this.FInText[0];

                this.FPosition.SliceCount = txt.Length;
                this.FWidth[0] = layout.Metrics.WidthIncludingTrailingWhitespace;
                this.FLayoutWidth[0] = layout.Metrics.LayoutWidth;
                this.FLeft[0] = layout.Metrics.Left;

                this.FPosition[0] = 0;
                string t = txt.Substring(0, 1);
                var ly = new TextLayout(this.dwFactory, t, format, 50000, 50000);
                lastwidth = ly.Metrics.WidthIncludingTrailingWhitespace;

                for (int i = 1; i < txt.Length; i++)
                {
                    t = txt.Substring(0, i + 1);
                    ly = new TextLayout(this.dwFactory, t, format, 50000, 50000);
                    float s = ly.Metrics.WidthIncludingTrailingWhitespace;
                    this.FPosition[i] = lastwidth;
                    lastwidth = s;
                }

            }
        }
Example #5
0
        protected override void OnCreateDeviceIndependentResources(Direct2DFactory factory)
        {
            base.OnCreateDeviceIndependentResources(factory);
            this._textFormat = DirectWriteFactory.CreateTextFormat("Gabriola", 72);
            this._textFormat.TextAlignment = TextAlignment.Center;
            this._textFormat.ParagraphAlignment = ParagraphAlignment.Center;
            float width = ClientSize.Width / dpiScaleX;
            float height = ClientSize.Height / dpiScaleY;
            this._textLayout = DirectWriteFactory.CreateTextLayout("Click on this text Click on this text", this._textFormat, width, height);
            this._textAnalyzer = DirectWriteFactory.CreateTextAnalyzer();
            this._source = new MyTextSource("Click on this text Click on this text");
            using (FontCollection coll = this._textFormat.FontCollection)
            {
                int count = coll.Count;
                for (int index = 0; index < count; ++index)
                {
                    using (FontFamily ff = coll[index])
                    {
                        using (Font font = ff.GetFirstMatchingFont(FontWeight.Normal, FontStretch.Normal, FontStyle.Normal))
                        {
                            LocalizedStrings ls = font.FaceNames;
                            LocalizedStrings desc = font.GetInformationalStrings(InformationalStringId.Designer);

                            int cultureIndex = ls.FindCulture(CultureInfo.CurrentCulture);
                            string faceName = ls[cultureIndex];
                            FontMetrics metrics = font.Metrics;
                        }
                    }
                }
            }
            this._textAnalyzer.AnalyzeLineBreakpoints(_source, 0, (uint)_source.Text.Length);
            this._textAnalyzer.AnalyzeScript(_source, 0, (uint)_source.Text.Length);
        }
Example #6
0
 public HtmlListInfo(HtmlTag htmlTag, int columns = 0, object htmlAttributes = null, TextLayout textLayout = TextLayout.Default)
 {
     HtmlTag = htmlTag;
     Columns = columns;
     HtmlAttributes = htmlAttributes;
     TextLayout = textLayout;
 }
        protected override void OnCreateDeviceIndependentResources(Direct2DFactory factory)
        {
            base.OnCreateDeviceIndependentResources(factory);

            this._textFormat = DirectWriteFactory.CreateTextFormat("Gabriola",
                FontWeight.Normal,
                FontStyle.Normal,
                FontStretch.Normal,
                72);

            this._textFormat.TextAlignment = TextAlignment.Center;
            this._textFormat.ParagraphAlignment = ParagraphAlignment.Center;

            float width = ClientSize.Width / _dpiScaleX;
            float height = ClientSize.Height / _dpiScaleY;

            this._textLayout = DirectWriteFactory.CreateTextLayout(
                _text,
                this._textFormat,
                width,
                height);

            this._textLayout.SetFontSize(100, new TextRange(20, 6));
            this._textLayout.SetUnderline(true, new TextRange(20, 11));
            this._textLayout.SetFontWeight(FontWeight.Bold, new TextRange(20, 11));

            using (Typography typography = DirectWriteFactory.CreateTypography())
            {
                typography.AddFontFeature(FontFeatureTag.StylisticSet7, 1);
                this._textLayout.SetTypography(typography, new TextRange(0, _text.Length));
            }
        }
Example #8
0
        public void Evaluate(int SpreadMax)
        {
            if (!this.FFormat.PluginIO.IsConnected)
            {
                this.FOutput.SliceCount = 0;
                return;
            }

            if (this.FFormat.IsChanged || this.FMaxHeight.IsChanged || this.FMaxWidth.IsChanged
                || this.FText.IsChanged || this.FTextAlign.IsChanged || this.FParaAlign.IsChanged)
            {
                this.FOutput.SliceCount = SpreadMax;

                for (int i = 0; i < this.FOutput.SliceCount; i++)
                {
                    if (this.FOutput[i] != null) { this.FOutput[i].Dispose(); }
                }

                for (int i = 0; i < SpreadMax; i++)
                {
                    var tl = new TextLayout(this.dwFactory, this.FText[i], this.FFormat[i], this.FMaxWidth[i], this.FMaxHeight[i]);
                    tl.TextAlignment = this.FTextAlign[i];
                    tl.ParagraphAlignment = this.FParaAlign[i];
                    this.FOutput[i] = tl;
                }
            }
        }
Example #9
0
 internal TextShape(Paint2DForm parent, TextLayout textLayout, Point2F startPoint, float maxX, float maxY, int selectedBrush)
     : base(parent)
 {
     _maxX = maxX;
     _maxY = maxY;
     _textLayout = textLayout;
     _selectedBrushIndex = selectedBrush;
     _point0 = startPoint;
 }
Example #10
0
 protected override void OnCreateDeviceIndependentResources(Direct2DFactory factory)
 {
     base.OnCreateDeviceIndependentResources(factory);
     this._textFormat = DirectWriteFactory.CreateTextFormat("Gabriola", 72);
     this._textFormat.TextAlignment = TextAlignment.Center;
     this._textFormat.ParagraphAlignment = ParagraphAlignment.Center;
     float width = ClientSize.Width / dpiScaleX;
     float height = ClientSize.Height / dpiScaleY;
     this._textLayout = DirectWriteFactory.CreateTextLayout("Click on this text", this._textFormat, width, height);
 }
            protected override void DoApply(TextLayout layout, TextRange range)
            {
                Typography tp = new Typography(this.dwFactory);
                tp.AddFeature(new FontFeature()
                    {
                        NameTag = tag,
                        Value = 1
                    });

                layout.SetTypography(tp, range);
            }
    public HtmlListInfo(
      HtmlTag htmlTag,
      int columns = 0,
      object htmlAttributes = null,
      TextLayout textLayout = TextLayout.Default,
      TemplateIsUsed templateIsUsed = TemplateIsUsed.No) {

      this.htmlTag = htmlTag;
      Columns = columns;
      this.htmlAttributes = htmlAttributes;
      TextLayout = textLayout;
      TemplateIsUsed = templateIsUsed;
    }
Example #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TextRenderUnit" /> class.
        /// </summary>
        /// <param name="textLayout">The text layout.</param>
        /// <param name="brush">The brush.</param>
        /// <param name="transform">The text transform.</param>
        public TextRenderUnit(TextLayout textLayout, Brush brush, Matrix3x2 transform)
        {
            this.layout = textLayout;
            this.brush = brush;
            this.transform = transform;

            var topleft = Matrix3x2.TransformPoint(transform, new Vector2(0, 0));
            var bottomRight = Matrix3x2.TransformPoint(transform, new Vector2(textLayout.Metrics.Width, textLayout.Metrics.Height));

            this.bounds = new RectangleF
            {
                Top = topleft.Y,
                Left = topleft.X,
                Right = bottomRight.X,
                Bottom = bottomRight.Y
            };
        }
Example #14
0
        private void CreateDeviceIndependentResources()
        {
            // Create the D2D Factory
            d2dFactory = D2DFactory.CreateFactory(D2DFactoryType.SingleThreaded);

            // Create the DWrite Factory
            dwriteFactory = DWriteFactory.CreateFactory();

            wicFactory = new ImagingFactory();

            string text = "Inline Object * Sample";

            textFormat = dwriteFactory.CreateTextFormat("Gabriola", 72);

            textFormat.TextAlignment = DWrite.TextAlignment.Center;
            textFormat.ParagraphAlignment = DWrite.ParagraphAlignment.Center;
    
            textLayout = dwriteFactory.CreateTextLayout(
                text,
                textFormat,
                (float) host.ActualWidth,
                (float) host.ActualHeight);
        }
Example #15
0
        public void Should_HitTestTextRange()
        {
            using (Start())
            {
                var layout = new TextLayout(
                    SingleLineText,
                    Typeface.Default,
                    12.0f,
                    Brushes.Black.ToImmutable());

                var lineRects = layout.HitTestTextRange(0, SingleLineText.Length).ToList();

                Assert.Equal(layout.TextLines.Count, lineRects.Count);

                for (var i = 0; i < layout.TextLines.Count; i++)
                {
                    var textLine = layout.TextLines[i];
                    var rect     = lineRects[i];

                    Assert.Equal(textLine.WidthIncludingTrailingWhitespace, rect.Width);
                }

                var rects = layout.TextLines.SelectMany(x => x.TextRuns.Cast <ShapedTextCharacters>())
                            .SelectMany(x => x.ShapedBuffer.GlyphAdvances).ToArray();

                for (var i = 0; i < SingleLineText.Length; i++)
                {
                    for (var j = 1; i + j < SingleLineText.Length; j++)
                    {
                        var expected = rects.AsSpan(i, j).ToArray().Sum();
                        var actual   = layout.HitTestTextRange(i, j).Sum(x => x.Width);

                        Assert.Equal(expected, actual);
                    }
                }
            }
        }
Example #16
0
        protected override void OnCreateDeviceIndependentResources(Direct2DFactory factory)
        {
            base.OnCreateDeviceIndependentResources(factory);
            _textFormat = DirectWriteFactory.CreateTextFormat("Gabriola", 72);
            _textFormat.TextAlignment      = TextAlignment.Center;
            _textFormat.ParagraphAlignment = ParagraphAlignment.Center;
            float width  = ClientSize.Width / dpiScaleX;
            float height = ClientSize.Height / dpiScaleY;

            _textLayout   = DirectWriteFactory.CreateTextLayout("Click on this text Click on this text", _textFormat, width, height);
            _textAnalyzer = DirectWriteFactory.CreateTextAnalyzer();
            _source       = new MyTextSource("Click on this text Click on this text");
            using (FontCollection coll = _textFormat.FontCollection)
            {
                int count = coll.Count;
                for (int index = 0; index < count; ++index)
                {
                    using (FontFamily ff = coll[index])
                    {
                        using (Font font = ff.GetFirstMatchingFont(FontWeight.Normal, FontStretch.Normal, FontStyle.Normal))
                        {
                            LocalizedStrings ls   = font.FaceNames;
                            LocalizedStrings desc = font.GetInformationalStrings(InformationalStringId.Designer);

                            int cultureIndex = ls.FindCulture(CultureInfo.CurrentCulture);
                            if (cultureIndex >= 0)
                            {
                                string      faceName = ls[cultureIndex];
                                FontMetrics metrics  = font.Metrics;
                            }
                        }
                    }
                }
            }
            _textAnalyzer.AnalyzeLineBreakpoints(_source, 0, (uint)_source.Text.Length);
            _textAnalyzer.AnalyzeScript(_source, 0, (uint)_source.Text.Length);
        }
Example #17
0
        public void Should_Apply_TextSpan_To_Unicode_String_In_Between()
        {
            using (Start())
            {
                const string text = "😄😄😄😄";

                var foreground = new SolidColorBrush(Colors.Red).ToImmutable();

                var spans = new[]
                {
                    new TextStyleRun(
                        new TextPointer(2, 2),
                        new TextStyle(Typeface.Default, 12, foreground))
                };

                var layout = new TextLayout(
                    text,
                    Typeface.Default,
                    12.0f,
                    Brushes.Black.ToImmutable(),
                    textStyleOverrides: spans);

                var textLine = layout.TextLines[0];

                Assert.Equal(3, textLine.TextRuns.Count);

                var textRun = textLine.TextRuns[1];

                Assert.Equal(2, textRun.Text.Length);

                var actual = textRun.Text.Buffer.Span.ToString();

                Assert.Equal("😄", actual);

                Assert.Equal(foreground, textRun.Style.Foreground);
            }
        }
Example #18
0
        /// <summary>
        /// Draw our text on the screen
        /// </summary>
        /// <param name="Text"></param>
        /// <param name="vAlign"></param>
        /// <param name="hAlign"></param>
        /// <param name="DrawBrush"></param>
        /// <param name="Format"></param>
        private void DrawString(string Text, VerticalAlignment vAlign, HorizontalAlignment hAlign, Brush DrawBrush, TextFormat Format, float XMultiplier = 1, float YMultiplier = 1)
        {
            using (TextLayout t = new TextLayout(Surface.FactoryDirectWrite, Text, Format, Surface.ClientRectangle.Width, Surface.ClientRectangle.Height))
            {
                Vector2    TextSize = new Vector2(t.Metrics.Width, t.Metrics.Height);
                RawVector2 TextPos  = new RawVector2(0, 0);

                if (vAlign == VerticalAlignment.Top)
                {
                    TextPos.Y = TextSize.Y * (YMultiplier - 1);
                }
                else if (vAlign == VerticalAlignment.Center)
                {
                    TextPos.Y = (t.MaxHeight - (TextSize.Y * YMultiplier)) / 2f;
                }
                else if (vAlign == VerticalAlignment.Bottom)
                {
                    TextPos.Y = (t.MaxHeight - (TextSize.Y * YMultiplier));
                }

                if (hAlign == HorizontalAlignment.Left)
                {
                    TextPos.X = TextSize.X * (XMultiplier - 1);
                }
                else if (hAlign == HorizontalAlignment.Center)
                {
                    TextPos.X = (t.MaxWidth - (TextSize.X * XMultiplier)) / 2f;
                }
                else if (hAlign == HorizontalAlignment.Right)
                {
                    TextPos.X = t.MaxWidth - (TextSize.X * XMultiplier);
                }


                Surface.RenderTarget2D.DrawTextLayout(TextPos, t, DrawBrush);
            }
        }
Example #19
0
        /// <summary>
        /// 取得字符对应的宽度
        /// </summary>
        /// <param name="character"></param>
        /// <returns></returns>
        private float GetCharacterWidth(Character character)
        {
            DWriteFactory dwFactory  = new DWriteFactory(SharpDX.DirectWrite.FactoryType.Shared);
            Vector2       offset     = new Vector2(0.0f, 0.0f);
            TextFormat    textFormat = new TextFormat(dwFactory,
                                                      character.font.FontFamily.Name,
                                                      character.font.Bold ? SharpDX.DirectWrite.FontWeight.Bold : SharpDX.DirectWrite.FontWeight.Regular,
                                                      character.font.Italic ? SharpDX.DirectWrite.FontStyle.Italic : SharpDX.DirectWrite.FontStyle.Normal,
                                                      character.font.Size);
            TextLayout textLayout = new TextLayout(dwFactory,
                                                   "好" + character.content,
                                                   textFormat,
                                                   this.pageWidth,
                                                   this.pageHeight);

            textLayout.SetUnderline(character.font.Underline, new TextRange(0, character.content.Length));
            textLayout.SetFontStyle(character.font.Italic ? FontStyle.Italic : FontStyle.Normal, new TextRange(0, character.content.Length));
            textLayout.SetFontWeight(character.font.Bold ? FontWeight.Bold : FontWeight.Normal, new TextRange(0, character.content.Length));
            ClusterMetrics[] clusterMetrics = textLayout.GetClusterMetrics();

            float result          = 0.0f;
            float prefixCharWidth = clusterMetrics[0].Width;

            foreach (ClusterMetrics v in clusterMetrics)
            {
                result += v.Width;
            }

            dwFactory.Dispose();
            textFormat.Dispose();
            textLayout.Dispose();
            dwFactory  = null;
            textFormat = null;
            textLayout = null;

            return(result - prefixCharWidth);
        }
Example #20
0
        public void PushText(string Text, ConsoleColor Color)
        {
            if (!Base.TheBox)
            {
                MessageQueue.Add(Tuple.Create(Text, Color, false));
                return;
            }
            TextLayout tl = null;

            try {
                tl = new TextLayout(
                    Base.DWFactory,
                    Text,
                    Base.DefaultTextFormat,
                    Screen.ScreenSize.Width,
                    Screen.ScreenSize.Height);
            } catch (Exception ex) {
                Debugger.Break();
            }
            lock (ScreenElementsLock) {
                ScreenElements.Add(new TextElement(tl, null, Text, Color));
                TextElementsHeight += tl.Metrics.Height;
            }
        }
Example #21
0
        public GUICheckbox(int x, int y, int w, int h, string text, Action onClickDelegate)
        {
            PositionX        = x;
            PositionY        = y;
            Width            = w;
            Height           = h;
            Text             = text;
            OnClickDelegate += onClickDelegate;
            OnClickDelegate += HandleClick;

            BackgroundColor      = Color.White;
            BorderColor          = Color.BlanchedAlmond;
            BackgroundColorHover = Color.AntiqueWhite;
            BorderColorHover     = Color.Bisque;
            TextColor            = Color.WhiteSmoke;

            TextFormat = new TextFormat(FactoryDWrite, "Calibri", 20)
            {
                TextAlignment = TextAlignment.Leading, ParagraphAlignment = ParagraphAlignment.Center
            };
            TextLayout = new TextLayout(FactoryDWrite, Text, TextFormat, Width - 25, Height);

            _state = ChecboxState.Unchecked;
        }
Example #22
0
        public override void Render()
        {
            if (isFadeOut && FadeAnimation.Value == 1)
            {
                return;
            }

            using (var layer = new Layer(DeviceContext))
            {
                parameter.Opacity = (isFadeOut ? 1 - FadeAnimation.Value : FadeAnimation.Value);
                DeviceContext.PushLayer(ref parameter, layer);

                using (var layout = new TextLayout(Container.DWFactory, $"Now Loading...", format, float.PositiveInfinity, float.PositiveInfinity))
                    using (var layout2 = new TextLayout(Container.DWFactory, "🕛", format, float.PositiveInfinity, float.PositiveInfinity))
                    {
                        const int Radius      = 5;
                        const int Margin      = 20;
                        const int SplitMargin = 5;

                        DeviceContext.FillRoundedRectangle(new RoundedRectangle
                        {
                            RadiusX = Radius,
                            RadiusY = Radius,
                            Rect    = new RawRectangleF(Container.WindowWidth - layout.Metrics.Width - SplitMargin - layout2.Metrics.Width - Margin - Radius * 2, Container.WindowHeight - layout.Metrics.Height - Margin - Radius * 2, Container.WindowWidth - Radius * 2, Container.WindowHeight - Radius * 2)
                        }, Resource.Get <BrushResource>("Back").Brush);

                        DeviceContext.DrawTextLayout(new RawVector2(Container.WindowWidth - layout.Metrics.Width - Margin, Container.WindowHeight - layout.Metrics.Height - Margin), layout, Resource.Get <BrushResource>("Fore").Brush);

                        var origin = new Vector2(Container.WindowWidth - layout.Metrics.Width - SplitMargin - layout2.Metrics.Width - Margin, Container.WindowHeight - layout.Metrics.Height - Margin);
                        DeviceContext.Transform = Matrix3x2.Rotation(LoopAnimation.Value * 360 * (float)Math.PI / 180, origin + new Vector2(layout2.Metrics.Width / 2, layout.Metrics.Height / 2));
                        DeviceContext.DrawTextLayout(origin, layout2, Resource.Get <BrushResource>("Fore").Brush);
                        DeviceContext.Transform = Matrix3x2.Identity;
                    }
                DeviceContext.PopLayer();
            }
        }
Example #23
0
        /// <summary>
        /// This method is called once per game loop after calling Update. Like Update, the Render()
        /// method is also called from the main class. This is the method where the graphics pipeline
        /// is constructed and processed for the frame using methods on the ID3D11DeviceContext instance.
        ///
        /// It’s important to understand that this call (or other similar Draw* calls defined on
        /// ID3D11DeviceContext) actually executes the pipeline.
        /// https://msdn.microsoft.com/en-us/library/windows/desktop/dn643746(v=vs.85).aspx
        ///
        /// Specifically, this is when Direct3D communicates with the GPU to set drawing state, runs
        /// each pipeline stage, and writes the pixel results into the render-target buffer resource
        /// for display by the swap chain.
        ///
        /// Since communication between the CPU and GPU incurs overhead, combine multiple draw calls
        /// into a single one if you can, especially if your scene has a lot of rendered objects.
        /// </summary>
        ///
        /// OnRender will Call each Active GameObjects to be Rendered
        protected override void OnRender()
        {
            //clear previous frame
            RenderTarget2D.Clear(null);

            //if display mouse coords  -- add a checkbox or option menu later \

            //Display Mouse coordinates:  top left corner : (0,0)
            TextLayout.Dispose();
            TextLayout = new TextLayout(FactoryDWrite, _mousePosition.GetMouseCoordinates(), TextFormat, 400, 40);
            RenderTarget2D.DrawTextLayout(new Vector2(0, 0), TextLayout, SceneColorBrush, DrawTextOptions.None);

            //and all added lines
            foreach (IRenderableItem item in _drawings)
            {
                item.Render(RenderTarget2D);
            }

            //Render current line if not null "?." operator
            ((IRenderableItem)_currentDrawing)?.Render(RenderTarget2D);

            //At last, display GUI on top of everything
            _guiManager.Render(RenderTarget2D);
        }
Example #24
0
        /// <summary>
        /// Obtains the current caret position (in untransformed space)</summary>
        /// <returns>Current caret position rectangle (in untransformed space)</returns>
        public RectangleF GetCaretRect()
        {
            if (TextLayout == null)
            {
                return(new RectangleF());
            }

            var   caretMetrics = TextLayout.HitTestTextPosition(m_caretPosition, m_caretPositionOffset > 0);
            float caretX       = caretMetrics.Point.X;
            float caretY       = caretMetrics.Point.Y;

            UpdateSelectionRange();
            // If a selection exists, draw the caret using the
            // line size rather than the font size.
            if (SelectionLength > 0)
            {
                var lineMetrics = TextLayout.HitTestTextRange(m_caretPosition, 0, 0, 0);
                caretY = lineMetrics[0].Top;
            }

            const int caretThickness = 1;

            return(new RectangleF(caretX - caretThickness / 2.0f, caretY, caretThickness, caretMetrics.Height));
        }
Example #25
0
 protected override void OnBoundsChanged()
 {
     if (minTextSize.IsZero && !string.IsNullOrEmpty(descriptionLabel.Text))
     {
         var measureLayout = new TextLayout {
             Text = descriptionLabel.Text,
             Font = descriptionLabel.Font
         };
         minTextSize = measureLayout.GetSize();
     }
     if (descriptionLabel.Size.Width < minTextSize.Width)
     {
         TooltipText = descriptionLabel.Text;
         descriptionLabel.Ellipsize        = EllipsizeMode.End;
         descriptionLabel.ExpandHorizontal = true;
     }
     else
     {
         TooltipText = string.Empty;
         descriptionLabel.Ellipsize        = EllipsizeMode.None;
         descriptionLabel.ExpandHorizontal = false;
     }
     base.OnBoundsChanged();
 }
Example #26
0
        internal protected override void OptionsChanged()
        {
            var layout = new TextLayout(Editor);

            layout.Font = Editor.Options.Font;
            string groupString = new string ('0', Editor.Options.GroupBytes * 2);

            layout.Text = groupString + " ";
            double lineHeight;
            var    sz = layout.GetSize();

            groupWidth = sz.Width;
            lineHeight = sz.Height;

            Data.LineHeight = lineHeight;

            layout.Text = "00";
            byteWidth   = layout.GetSize().Width;

            layout.Dispose();

//			tabArray = new Pango.TabArray (1, true);
//			tabArray.SetTab (0, Pango.TabAlign.Left, groupWidth);
        }
Example #27
0
        public void DrawText(RectangleF position, string text, Color color, RendererFontFlags flags = RendererFontFlags.Left, float fontSize = 13f, string fontFamily = "Calibri")
        {
            var font  = this.textFormatCache.GetOrCreate(fontFamily, fontSize);
            var brush = this.brushCache.GetOrCreate(color);

            using (var layout = new TextLayout(this.context.DirectWrite, text, font, position.Width, position.Height))
            {
                if ((flags & RendererFontFlags.Center) == RendererFontFlags.Center)
                {
                    layout.TextAlignment = TextAlignment.Center;
                }
                else if ((flags & RendererFontFlags.Right) == RendererFontFlags.Right)
                {
                    layout.TextAlignment = TextAlignment.Trailing;
                }

                if ((flags & RendererFontFlags.VerticalCenter) == RendererFontFlags.VerticalCenter)
                {
                    position.Y = (position.Y + (position.Height / 2)) - (font.FontSize / 2);
                }

                this.context.RenderTarget.DrawTextLayout(new RawVector2(position.X, position.Y), layout, brush);
            }
        }
Example #28
0
        void CalculateWidth()
        {
            using (var layout = new TextLayout(editor.TextArea)) {
                layout.Font = gutterFont;
                layout.Text = (LineCountMax.ToString());
                //layout.Alignment = Pango.Alignment.Left;
                layout.Width = -1;

                var sz = layout.GetSize();
                width = sz.Width + 4;
                //var height = sz.Height;

                if (!editor.Options.ShowFoldMargin)
                {
                    this.width += 2;
                }
                fontHeight = sz.Height;

                /*
                 * using (var metrics = editor.PangoContext.GetMetrics (layout.FontDescription, editor.PangoContext.Language)) {
                 *      fontHeight = System.Math.Ceiling (0.5 + (metrics.Ascent + metrics.Descent) / Pango.Scale.PangoScale);
                 * }*/
            }
        }
Example #29
0
        protected override LayoutWrapper RenderLine(long line)
        {
            var layout = new TextLayout(Editor);

            layout.Font = Editor.Options.Font;
            StringBuilder sb          = new StringBuilder();
            long          startOffset = line * Editor.BytesInRow;
            long          endOffset   = System.Math.Min(startOffset + Editor.BytesInRow, Data.Length);

            byte[] lineBytes = Data.GetBytes(startOffset, (int)(endOffset - startOffset));
            for (int i = 0; i < lineBytes.Length; i++)
            {
                byte b  = lineBytes[i];
                char ch = (char)b;
                if (b < 128 && (Char.IsLetterOrDigit(ch) || Char.IsPunctuation(ch)))
                {
                    sb.Append(ch);
                }
                else
                {
                    sb.Append(".");
                }
            }

            layout.Text = sb.ToString();
            Margin.LayoutWrapper result = new LayoutWrapper(layout);
            if (Data.IsSomethingSelected)
            {
                ISegment selection = Data.MainSelection.Segment;
                HandleSelection(selection.Offset, selection.EndOffset, startOffset, endOffset, null, delegate(long start, long end) {
                    result.Layout.SetForeground(Style.Selection, (int)(start - startOffset), (int)(end - start));
                    result.Layout.SetBackgound(Style.SelectionBg, (int)(start - startOffset), (int)(end - start));
                });
            }
            return(result);
        }
Example #30
0
            protected override void OnDraw(Context ctx, Rectangle dirtyRect)
            {
                base.OnDraw(ctx, dirtyRect);

                if (this.owner.titlebarvisible)
                {
                    var r = new Rectangle(dragsize, dragsize, this.Bounds.Width - dragsize * 2, TitleBar.TitleBarHeight);

                    ctx.SetColor(DockPanel.TitlebarColor);
                    ctx.Rectangle(r);
                    ctx.Fill();

                    var tl = new TextLayout(this)
                    {
                        Text = this.owner.Title
                    };

                    ctx.SetColor(Colors.Black);
                    ctx.DrawTextLayout(tl, new Point(dragsize + 4, dragsize + 2));
                }
                ctx.SetColor(Colors.Black);
                ctx.Rectangle(this.Bounds);
                ctx.Stroke();
            }
Example #31
0
        [InlineData("abcde\u000D", 6)] // Carriage Return
        public void Should_Break_With_BreakChar(string text, int expectedLength)
        {
            using (Start())
            {
                var layout = new TextLayout(
                    text,
                    Typeface.Default,
                    12.0f,
                    Brushes.Black.ToImmutable());

                Assert.Equal(2, layout.TextLines.Count);

                Assert.Equal(1, layout.TextLines[0].TextRuns.Count);

                Assert.Equal(expectedLength, ((ShapedTextRun)layout.TextLines[0].TextRuns[0]).GlyphRun.GlyphClusters.Length);

                Assert.Equal(5, ((ShapedTextRun)layout.TextLines[0].TextRuns[0]).GlyphRun.GlyphClusters[5]);

                if (expectedLength == 7)
                {
                    Assert.Equal(5, ((ShapedTextRun)layout.TextLines[0].TextRuns[0]).GlyphRun.GlyphClusters[6]);
                }
            }
        }
Example #32
0
        public void Evaluate(int SpreadMax)
        {
            if (!this.FFormat.PluginIO.IsConnected)
            {
                this.FOutput.SliceCount = 0;
                return;
            }

            if (this.FFormat.IsChanged || this.FMaxHeight.IsChanged || this.FMaxWidth.IsChanged ||
                this.FText.IsChanged || this.FTextAlign.IsChanged || this.FParaAlign.IsChanged)
            {
                //first dispose old outputs
                for (int i = 0; i < this.FOutput.SliceCount; i++)
                {
                    if (this.FOutput[i] != null)
                    {
                        this.FOutput[i].Dispose();
                    }
                }

                //then set new slicecount
                this.FOutput.SliceCount = SpreadMax;

                //then create new outputs
                for (int i = 0; i < SpreadMax; i++)
                {
                    float maxw  = this.FMaxWidth[i] > 0.0f ? this.FMaxWidth[i] : 0.0f;
                    float maxh  = this.FMaxHeight[i] > 0.0f ? this.FMaxHeight[i] : 0.0f;
                    var   tl    = new TextLayout(this.dwFactory, this.FText[i], this.FFormat[i], maxw, maxh);
                    var   align = (int)this.FTextAlign[i];
                    tl.TextAlignment      = (TextAlignment)align;
                    tl.ParagraphAlignment = this.FParaAlign[i];
                    this.FOutput[i]       = tl;
                }
            }
        }
Example #33
0
        public void Should_Apply_TextStyleSpan_To_Text_At_Start()
        {
            using (Start())
            {
                var foreground = new SolidColorBrush(Colors.Red).ToImmutable();

                var spans = new[]
                {
                    new TextStyleRun(
                        new TextPointer(0, 2),
                        new TextStyle(Typeface.Default, 12, foreground))
                };

                var layout = new TextLayout(
                    s_singleLineText,
                    Typeface.Default,
                    12.0f,
                    Brushes.Black.ToImmutable(),
                    textStyleOverrides: spans);

                var textLine = layout.TextLines[0];

                Assert.Equal(2, textLine.TextRuns.Count);

                var textRun = textLine.TextRuns[0];

                Assert.Equal(2, textRun.Text.Length);

                var actual = s_singleLineText.Substring(textRun.Text.Start,
                                                        textRun.Text.Length);

                Assert.Equal("01", actual);

                Assert.Equal(foreground, textRun.Style.Foreground);
            }
        }
Example #34
0
 protected abstract void DoApply(TextLayout layout, TextRange range);
Example #35
0
        private void DrawLegendLine(MM_DisplayParameter state, Vector2 start, Vector2 end, bool drawKVText = false, bool drawEnergizationState = false)
        {
            if (_legendFont == null || _legendFont.IsDisposed)
            {
                _legendFont = null;
                _legendFont = Surface.Fonts.GetTextFormat(MM_Repository.OverallDisplay.NetworkMapFont);
            }

            var color = state.ForeColor;

            var width  = state.Width;
            var stroke = state.DashStyle;

            var style = _solidStyle;

            if (stroke == System.Drawing.Drawing2D.DashStyle.Dash)
            {
                style = _dashStyle;
            }
            else if (stroke == System.Drawing.Drawing2D.DashStyle.DashDot || stroke == System.Drawing.Drawing2D.DashStyle.DashDotDot)
            {
                style = _dotDashStyle;
            }

            var brush = Surface.Brushes.GetBrush(color, 1f);

            if (drawKVText)
            {
                TextLayout textLayout = null;
                string     text       = state.Name.Split('.')[0];
                if (!_strings.TryGetValue(text, out textLayout) || textLayout == null || textLayout.IsDisposed)
                {
                    textLayout = new TextLayout(Surface.FactoryDirectWrite, text ?? string.Empty, _legendFont, end.X - start.X - 2, 16)
                    {
                        WordWrapping = WordWrapping.NoWrap
                    };
                    _strings[text] = textLayout;
                }
                Surface.RenderTarget2D.DrawTextLayout(start + Vector2.One, textLayout, brush, DrawTextOptions.Clip);
            }

            if (drawEnergizationState)
            {
                TextLayout textLayout = null;
                string     text       = state.Name.Split('.')[1];
                if (!_strings.TryGetValue(text, out textLayout) || textLayout == null || textLayout.IsDisposed)
                {
                    textLayout = new TextLayout(Surface.FactoryDirectWrite, text ?? string.Empty, _legendFont, end.X - start.X - 2, 12)
                    {
                        WordWrapping = WordWrapping.NoWrap
                    };
                    _strings[text] = textLayout;
                }
                Surface.RenderTarget2D.DrawTextLayout(start + new Vector2(1, -textLayout.Metrics.Height - 3), textLayout, Surface.Brushes.GetBrush(SharpDX.Color.White), DrawTextOptions.Clip);
            }

            if (_isBlinking || !state.Blink)
            {
                // offset by half a pixel to get hard lines
                bool offsetHalf = width - Math.Truncate(width) > 0 || ((int)width % 2 == 1);
                var  aa         = Surface.RenderTarget2D.AntialiasMode;
                Surface.RenderTarget2D.AntialiasMode = AntialiasMode.Aliased;
                Surface.RenderTarget2D.DrawLine(start + new Vector2(0, offsetHalf ? 0.5f : 0), end + new Vector2(0, offsetHalf ? 0.5f : 0), brush, width, style);
                Surface.RenderTarget2D.AntialiasMode = aa;
            }
        }
Example #36
0
 protected override void DoApply(TextLayout layout, TextRange range)
 {
     layout.SetFontWeight(this.Style, range);
 }
Example #37
0
        private static void GetKerningInfo(CCRawList <char> charset)
        {
            _abcValues.Clear();

            var fontFace = new FontFace(_currentFont);

            var value = new ABCFloat[1];

            var glyphRun = new GlyphRun();

            glyphRun.FontFace = fontFace;
            glyphRun.FontSize = _currentDIP;

            var BrushColor = SharpDX.Color.White;

            /*
             * SharpDX.DirectWrite.Matrix mtrx = new SharpDX.DirectWrite.Matrix();
             * mtrx.M11 = 1F;
             * mtrx.M12 = 0;
             * mtrx.M21 = 0;
             * mtrx.M22 = 1F;
             * mtrx.Dx = 0;
             * mtrx.Dy = 0;
             */
            //GlyphMetrics[] metrics = fontFace.GetGdiCompatibleGlyphMetrics(23, 1, mtrx, false, glyphIndices, false);

            //FontMetrics metr = fontFace.GetGdiCompatibleMetrics(23, 1, new SharpDX.DirectWrite.Matrix());
            //_pRenderTarget.DrawGlyphRun(new SharpDX.DrawingPointF(left, top), glyphRun, new SharpDX.Direct2D1.SolidColorBrush(_pRenderTarget, BrushColor), MeasuringMode.GdiClassic);
            int[] codePoints = new int[1];
            var   unitsPerEm = fontFace.Metrics.DesignUnitsPerEm;
            var   familyName = _currentFont.ToString();


            for (int i = 0; i < charset.Count; i++)
            {
                var ch = charset[i];
                if (!_abcValues.ContainsKey(ch))
                {
                    var textLayout = new TextLayout(FactoryDWrite, ch.ToString(), textFormat, unitsPerEm, unitsPerEm);

                    var tlMetrics = textLayout.Metrics;
                    var tlmWidth  = tlMetrics.Width;
                    var tllWidth  = tlMetrics.LayoutWidth;

                    codePoints[0] = (int)ch;
                    short[] glyphIndices = fontFace.GetGlyphIndices(codePoints);
                    glyphRun.Indices = glyphIndices;

                    var metrics = fontFace.GetDesignGlyphMetrics(glyphIndices, false);

                    //var width = metrics[0].AdvanceWidth + metrics[0].LeftSideBearing + metrics[0].RightSideBearing;
                    //var glyphWidth = _currentFontSizeEm * (float)metrics[0].AdvanceWidth / unitsPerEm;
                    //var abcWidth = _currentDIP * (float)width / unitsPerEm;

                    //value[0].abcfA = _currentFontSizeEm * (float)metrics[0].LeftSideBearing / unitsPerEm;
                    //value[0].abcfB = _currentFontSizeEm * (float)metrics[0].AdvanceWidth / unitsPerEm;
                    //value[0].abcfC = _currentFontSizeEm * (float)metrics[0].RightSideBearing / unitsPerEm;

                    // The A and C values are throwing the spacing off
                    //value[0].abcfA = _currentDIP * (float)metrics[0].LeftSideBearing / unitsPerEm;
                    value[0].abcfB = _currentDIP * (float)metrics[0].AdvanceWidth / unitsPerEm;
                    //value[0].abcfC = _currentDIP * (float)metrics[0].RightSideBearing / unitsPerEm;

                    _abcValues.Add(
                        ch,
                        new KerningInfo()
                    {
                        A = value[0].abcfA,
                        B = value[0].abcfB,
                        C = value[0].abcfC
                    });
                }
            }
        }
Example #38
0
 protected override void DoApply(TextLayout layout, TextRange range)
 {
     layout.SetUnderline(true, range);
 }
Example #39
0
        private void Render()
        {
            CreateDeviceResources();

            if (renderTarget.IsOccluded)
            {
                return;
            }

            SizeF renderTargetSize = renderTarget.Size;

            renderTarget.BeginDraw();

            renderTarget.Clear(new ColorF(1, 1, 1, 0));

            // Paint a grid background.
            RectF rf = new RectF(0.0f, 0.0f, renderTargetSize.Width, renderTargetSize.Height);

            renderTarget.FillRectangle(rf, gridPatternBitmapBrush);

            float curLeft = 0;

            rf = new RectF(
                curLeft,
                renderTargetSize.Height,
                (curLeft + renderTargetSize.Width / 5.0F),
                renderTargetSize.Height - renderTargetSize.Height * ((float)x1 / 100.0F));

            renderTarget.FillRectangle(rf, solidBrush1);

            textLayout = dwriteFactory.CreateTextLayout(String.Format("  {0}%", x1), textFormat, renderTargetSize.Width / 5.0F, 30);

            renderTarget.DrawTextLayout(
                new Point2F(curLeft, renderTargetSize.Height - 30),
                textLayout,
                blackBrush);

            curLeft = (curLeft + renderTargetSize.Width / 5.0F);
            rf      = new RectF(
                curLeft,
                renderTargetSize.Height,
                (curLeft + renderTargetSize.Width / 5.0F),
                renderTargetSize.Height - renderTargetSize.Height * ((float)x2 / 100.0F));
            renderTarget.FillRectangle(rf, radialGradientBrush);
            renderTarget.DrawText(
                String.Format("  {0}%", x2),
                textFormat,
                new RectF(curLeft, renderTargetSize.Height - 30, (curLeft + renderTargetSize.Width / 5.0F), renderTargetSize.Height), blackBrush);

            curLeft = (curLeft + renderTargetSize.Width / 5.0F);
            rf      = new RectF(
                curLeft,
                renderTargetSize.Height,
                (curLeft + renderTargetSize.Width / 5.0F),
                renderTargetSize.Height - renderTargetSize.Height * ((float)x3 / 100.0F));
            renderTarget.FillRectangle(rf, solidBrush3);
            renderTarget.DrawText(
                String.Format("  {0}%", x3),
                textFormat,
                new RectF(curLeft, renderTargetSize.Height - 30, (curLeft + renderTargetSize.Width / 5.0F), renderTargetSize.Height), blackBrush);

            curLeft = (curLeft + renderTargetSize.Width / 5.0F);
            rf      = new RectF(
                curLeft,
                renderTargetSize.Height,
                (curLeft + renderTargetSize.Width / 5.0F),
                renderTargetSize.Height - renderTargetSize.Height * ((float)x4 / 100.0F));
            renderTarget.FillRectangle(rf, linearGradientBrush);
            renderTarget.DrawText(
                String.Format("  {0}%", x4),
                textFormat,
                new RectF(curLeft, renderTargetSize.Height - 30, (curLeft + renderTargetSize.Width / 5.0F), renderTargetSize.Height), blackBrush);


            curLeft = (curLeft + renderTargetSize.Width / 5.0F);
            rf      = new RectF(
                curLeft,
                renderTargetSize.Height,
                (curLeft + renderTargetSize.Width / 5.0F),
                renderTargetSize.Height - renderTargetSize.Height * ((float)x5 / 100.0F));
            renderTarget.FillRectangle(rf, solidBrush2);
            renderTarget.DrawText(
                String.Format("  {0}%", x5),
                textFormat,
                new RectF(curLeft, renderTargetSize.Height - 30, (curLeft + renderTargetSize.Width / 5.0F), renderTargetSize.Height), blackBrush);

            renderTarget.EndDraw();
        }
Example #40
0
 public TextTool()
 {
     cursor_hand = new Gdk.Cursor (Gdk.Display.Default, PintaCore.Resources.GetIcon ("Cursor.Pan.png"), 8, 8);
     imContext = new Gtk.IMMulticontext ();
     imContext.Commit += OnIMCommit;
     layout = new TextLayout ();
 }
        public void Evaluate(int SpreadMax)
        {
            if (!this.FFormat.PluginIO.IsConnected)
            {
                this.FOutput.SliceCount = 0;
                return;
            }

            if (this.apply[0] || this.first)
            {
                this.FText.Sync();
                this.FTextAlign.Sync();
                this.FParaAlign.Sync();
                this.FMaxHeight.Sync();
                this.FMaxWidth.Sync();
                this.FFormat.Sync();
                this.textStyles.Sync();

                //first dispose old outputs
                for (int i = 0; i < this.FOutput.SliceCount; i++)
                {
                    if (this.FOutput[i] != null) { this.FOutput[i].Dispose(); }
                }

                //then set new slicecount
                this.FOutput.SliceCount = SpreadMax;

                //then create new outputs
                for (int i = 0; i < SpreadMax; i++)
                {
                    var tl = new TextLayout(this.dwFactory, this.FText[i], this.FFormat[i], this.FMaxWidth[i], this.FMaxHeight[i]);
                    var align = (int)this.FTextAlign[i];
                    tl.TextAlignment = (TextAlignment)align;
                    tl.ParagraphAlignment = this.FParaAlign[i];
                    var styles = textStyles[0];
                    for (int j = 0; j <styles.SliceCount; j++)
                    {
                        if (styles[j] != null)
                        {
                            styles[j].Apply(tl);
                        }
                    }

                    this.FOutput[i] = tl;
                }
            }
            this.first = false;
        }
 public TitleBarLayout(ActivityDesigner activityDesigner)
     : base(activityDesigner)
 {
     _textLayout = new TextLayout(activityDesigner);
     this.Layouts.Add(_textLayout);
     _imageLayout = new ImageLayout(activityDesigner);
     this.Layouts.Add(_imageLayout);
 }
Example #43
0
 protected override void DoApply(TextLayout layout, TextRange range)
 {
     layout.SetFontFamilyName(Name, range);
 }
Example #44
0
        /// <summary>
        /// Measures the string.
        /// </summary>
        /// <param name="text">The String.</param>
        /// <param name="font">The Font.</param>
        /// <returns>Vector2.</returns>
        public Vector2 MeasureString(string text, Font font)
        {
            var dxFont = font.Instance as DirectXFont;
            if (dxFont == null) throw new ArgumentException("DirectX10 expects a DirectXFont as resource.");

            TextFormat fontData = dxFont.GetFont();

            fontData.ParagraphAlignment = ParagraphAlignment.Near;
            fontData.TextAlignment = TextAlignment.Leading;
            fontData.WordWrapping = WordWrapping.NoWrap;

            using (
                var layout = new TextLayout(DirectXHelper.DirectWriteFactory, text, fontData, float.MaxValue,
                    float.MaxValue))
            {
                return new Vector2(layout.Metrics.Width, layout.Metrics.Height);
            }
        }
Example #45
0
        public void CreatePDF(Stream stream)
        {
            var doc      = new GcPdfDocument();
            var font     = StandardFonts.Times;
            var fontSize = 12;
            // 1/2" margins all around (72 dpi is the default resolution used by GcPdf):
            var margin     = 72 / 2;
            var pageWidth  = doc.PageSize.Width;
            var pageHeight = doc.PageSize.Height;
            var cW         = pageWidth - margin * 2;
            // Text format for the chapter titles:
            var tlCaption = new TextLayout(72);

            tlCaption.DefaultFormat.Font      = font;
            tlCaption.DefaultFormat.FontSize  = fontSize + 4;
            tlCaption.DefaultFormat.Underline = true;
            tlCaption.MaxWidth      = pageWidth;
            tlCaption.MaxHeight     = pageHeight;
            tlCaption.MarginLeft    = tlCaption.MarginTop = tlCaption.MarginRight = tlCaption.MarginBottom = margin;
            tlCaption.TextAlignment = TextAlignment.Center;
            // Height of chapter caption (use a const for simplicity):
            const float captionH = 24;
            // Text layout for main document body (default GcPdf resolution is 72dpi):
            var tl = new TextLayout(72);

            tl.DefaultFormat.Font     = font;
            tl.DefaultFormat.FontSize = fontSize;
            tl.FirstLineIndent        = 72 / 2;
            tl.MaxWidth              = pageWidth;
            tl.MaxHeight             = pageHeight;
            tl.MarginLeft            = tl.MarginRight = tl.MarginBottom = margin;
            tl.MarginTop             = margin + captionH;
            tl.ColumnWidth           = cW * 0.3f;
            tl.TextAlignment         = TextAlignment.Justified;
            tl.AlignmentDelayToSplit = true;
            // Array of PageSplitArea's which control additional columns (1st column is controlled by
            // the 'main' TextLayout, for each additional one a PageSplitArea must be provided -
            // it will create and return a TextLayout that can then be used to render the column):
            var psas = new PageSplitArea[]
            {
                new PageSplitArea(tl)
                {
                    MarginLeft = tl.MarginLeft + (cW * 0.35f)
                },
                new PageSplitArea(tl)
                {
                    ColumnWidth = -cW * 0.3f
                }
            };
            // Split options to control splitting text between pages:
            TextSplitOptions tso = new TextSplitOptions(tl)
            {
                RestMarginTop            = margin,
                MinLinesInFirstParagraph = 2,
                MinLinesInLastParagraph  = 2
            };
            // Generate a number of "chapters", provide outline entry for each:
            const int NChapters = 20;

            doc.Pages.Add();
            for (int i = 0; i < NChapters; ++i)
            {
                // Print chapter header across all columns:
                string chapter = $"Chapter {i + 1}";
                tlCaption.Clear();
                tlCaption.Append(chapter);
                tlCaption.PerformLayout(true);
                doc.Pages.Last.Graphics.DrawTextLayout(tlCaption, PointF.Empty);
                // Add outline node for the chapter:
                doc.Outlines.Add(new OutlineNode(chapter, new DestinationFitV(doc.Pages.Count - 1, null)));
                //
                // Clear last chapter's text and add new chapter:
                tl.FirstLineIsStartOfParagraph = true;
                tl.LastLineIsEndOfParagraph    = true;
                tl.Clear();
                tl.Append(Common.Util.LoremIpsum(5, 7, 9, 15, 25));
                tl.PerformLayout(true);
                // Variable to hold last chapter end's bottom coord:
                float contentBottom = 0f;
                // Print the chapter:
                var tls = new TextLayoutSplitter(tl);
                while (true)
                {
                    var tlCol0 = tls.SplitAndBalance(psas, tso);
                    var g      = doc.Pages.Last.Graphics;
                    g.DrawTextLayout(tlCol0, PointF.Empty);
                    g.DrawTextLayout(psas[0].TextLayout, PointF.Empty);
                    g.DrawTextLayout(psas[1].TextLayout, PointF.Empty);
                    if (tls.SplitResult != SplitResult.Split)
                    {
                        // End of chapter, find out how much height left on page for next chapter:
                        contentBottom = tl.ContentY + tl.ContentHeight;
                        contentBottom = Math.Max(contentBottom, psas[0].TextLayout.ContentRectangle.Bottom);
                        contentBottom = Math.Max(contentBottom, psas[1].TextLayout.ContentRectangle.Bottom);
                        // Done printing chapter:
                        break;
                    }
                    // Continue printing chapter on new page:
                    psas[0].MarginTop = psas[1].MarginTop = margin;
                    doc.Pages.Add();
                }
                // Next chapter - find out if we have enough space left on current page to start new chapter:
                if (contentBottom + captionH < pageHeight * 0.8f)
                {
                    // Start new chapter on current page:
                    contentBottom      += pageHeight * 0.05f;
                    tlCaption.MarginTop = contentBottom;
                    tl.MarginTop        = psas[0].MarginTop = psas[1].MarginTop = contentBottom + captionH;
                }
                else if (i < NChapters - 1)
                {
                    // Start new chapter on new page:
                    tlCaption.MarginTop = margin;
                    tl.MarginTop        = psas[0].MarginTop = psas[1].MarginTop = margin + captionH;
                    doc.Pages.Add();
                }
            }
            // Done:
            doc.Save(stream);
        }
Example #46
0
        protected override DX11VertexGeometry GetGeom(DX11RenderContext device, int slice)
        {
            if (d2dFactory == null)
            {
                d2dFactory = new D2DFactory();
                dwFactory  = new DWriteFactory(SharpDX.DirectWrite.FactoryType.Shared);
            }

            TextFormat fmt = new TextFormat(dwFactory, this.FFontInput[slice].Name, FFontSize[slice]);
            TextLayout tl  = new TextLayout(dwFactory, FText[slice], fmt, 0.0f, 32.0f);

            tl.WordWrapping       = WordWrapping.NoWrap;
            tl.TextAlignment      = FHAlignment[slice];
            tl.ParagraphAlignment = FVAlignment[slice];

            OutlineRenderer renderer = new OutlineRenderer(d2dFactory);
            Extruder        ex       = new Extruder(d2dFactory);


            tl.Draw(renderer, 0.0f, 0.0f);

            var outlinedGeometry = renderer.GetGeometry();

            ex.GetVertices(outlinedGeometry, vertexList, this.FExtrude[slice]);
            outlinedGeometry.Dispose();

            Vector3 min = new Vector3(float.MaxValue);
            Vector3 max = new Vector3(float.MinValue);

            for (int i = 0; i < vertexList.Count; i++)
            {
                Pos3Norm3VertexSDX pn = vertexList[i];

                min.X = pn.Position.X < min.X ? pn.Position.X : min.X;
                min.Y = pn.Position.Y < min.Y ? pn.Position.Y : min.Y;
                min.Z = pn.Position.Z < min.Z ? pn.Position.Z : min.Z;

                max.X = pn.Position.X > max.X ? pn.Position.X : max.X;
                max.Y = pn.Position.Y > max.Y ? pn.Position.Y : max.Y;
                max.Z = pn.Position.Z > max.Z ? pn.Position.Z : max.Z;
            }

            SlimDX.DataStream ds = new SlimDX.DataStream(vertexList.Count * Pos3Norm3VertexSDX.VertexSize, true, true);
            ds.Position = 0;

            for (int i = 0; i < vertexList.Count; i++)
            {
                ds.Write(vertexList[i]);
            }

            ds.Position = 0;

            var vbuffer = new SlimDX.Direct3D11.Buffer(device.Device, ds, new SlimDX.Direct3D11.BufferDescription()
            {
                BindFlags      = SlimDX.Direct3D11.BindFlags.VertexBuffer,
                CpuAccessFlags = SlimDX.Direct3D11.CpuAccessFlags.None,
                OptionFlags    = SlimDX.Direct3D11.ResourceOptionFlags.None,
                SizeInBytes    = (int)ds.Length,
                Usage          = SlimDX.Direct3D11.ResourceUsage.Default
            });

            ds.Dispose();

            DX11VertexGeometry vg = new DX11VertexGeometry(device);

            vg.InputLayout    = Pos3Norm3VertexSDX.Layout;
            vg.Topology       = SlimDX.Direct3D11.PrimitiveTopology.TriangleList;
            vg.VertexBuffer   = vbuffer;
            vg.VertexSize     = Pos3Norm3VertexSDX.VertexSize;
            vg.VerticesCount  = vertexList.Count;
            vg.HasBoundingBox = true;
            vg.BoundingBox    = new SlimDX.BoundingBox(new SlimDX.Vector3(min.X, min.Y, min.Z), new SlimDX.Vector3(max.X, max.Y, max.Z));

            renderer.Dispose();
            fmt.Dispose();
            tl.Dispose();

            return(vg);
        }
Example #47
0
        private void Render()
        {

            CreateDeviceResources();

            if (renderTarget.IsOccluded)
                return;

            SizeF renderTargetSize = renderTarget.Size;

            renderTarget.BeginDraw();

            renderTarget.Clear(new ColorF(1, 1, 1, 0));

            // Paint a grid background.
            RectF rf = new RectF(0.0f, 0.0f, renderTargetSize.Width, renderTargetSize.Height);
            renderTarget.FillRectangle(rf, gridPatternBitmapBrush);

            float curLeft = 0;

            rf = new RectF(
                curLeft,
                renderTargetSize.Height,
                (curLeft + renderTargetSize.Width / 5.0F),
                renderTargetSize.Height - renderTargetSize.Height * ((float)x1 / 100.0F));

            renderTarget.FillRectangle(rf, solidBrush1);

            textLayout = dwriteFactory.CreateTextLayout(String.Format("  {0}%", x1), textFormat, renderTargetSize.Width / 5.0F, 30);

            renderTarget.DrawTextLayout(
                new Point2F(curLeft, renderTargetSize.Height - 30),
                textLayout,
                blackBrush);

            curLeft = (curLeft + renderTargetSize.Width / 5.0F);
            rf = new RectF(
                curLeft,
                renderTargetSize.Height,
                (curLeft + renderTargetSize.Width / 5.0F),
                renderTargetSize.Height - renderTargetSize.Height * ((float)x2 / 100.0F));
            renderTarget.FillRectangle(rf, radialGradientBrush);
            renderTarget.DrawText(
                String.Format("  {0}%", x2),
                textFormat,
                new RectF(curLeft, renderTargetSize.Height - 30, (curLeft + renderTargetSize.Width / 5.0F), renderTargetSize.Height), blackBrush);

            curLeft = (curLeft + renderTargetSize.Width / 5.0F);
            rf = new RectF(
                curLeft,
                renderTargetSize.Height,
                (curLeft + renderTargetSize.Width / 5.0F),
                renderTargetSize.Height - renderTargetSize.Height * ((float)x3 / 100.0F));
            renderTarget.FillRectangle(rf, solidBrush3);
            renderTarget.DrawText(
                String.Format("  {0}%", x3),
                textFormat,
                new RectF(curLeft, renderTargetSize.Height - 30, (curLeft + renderTargetSize.Width / 5.0F), renderTargetSize.Height), blackBrush);

            curLeft = (curLeft + renderTargetSize.Width / 5.0F);
            rf = new RectF(
                curLeft,
                renderTargetSize.Height,
                (curLeft + renderTargetSize.Width / 5.0F),
                renderTargetSize.Height - renderTargetSize.Height * ((float)x4 / 100.0F));
            renderTarget.FillRectangle(rf, linearGradientBrush);
            renderTarget.DrawText(
                String.Format("  {0}%", x4),
                textFormat,
                new RectF(curLeft, renderTargetSize.Height - 30, (curLeft + renderTargetSize.Width / 5.0F), renderTargetSize.Height), blackBrush);


            curLeft = (curLeft + renderTargetSize.Width / 5.0F);
            rf = new RectF(
                curLeft,
                renderTargetSize.Height,
                (curLeft + renderTargetSize.Width / 5.0F),
                renderTargetSize.Height - renderTargetSize.Height * ((float)x5 / 100.0F));
            renderTarget.FillRectangle(rf, solidBrush2);
            renderTarget.DrawText(
                String.Format("  {0}%", x5),
                textFormat,
                new RectF(curLeft, renderTargetSize.Height - 30, (curLeft + renderTargetSize.Width / 5.0F), renderTargetSize.Height), blackBrush);

            renderTarget.EndDraw();

        }
    private void ApplyTextBlockFormat(TextLayout layout)
    {
      if (layout.Blocks.Count == 1)
      {
        TextLayoutBlock textBlock = layout.Blocks[0];
        if (!string.IsNullOrEmpty(textBlock.TextExpression))
        {
          string expr = textBlock.TextExpression;
          if (m_regexTextFormat.IsMatch(expr))
          {
            layout.Blocks.Clear();

            int p = 0;
            TextLayoutBlock tlb = null;

            foreach (Match match in m_regexTextFormat.Matches(expr))
            {
              if (p - match.Index > 0)
              {
                tlb = (TextLayoutBlock)textBlock.Clone();
                tlb.TextExpression = ReplaceQuotes(Regex.Replace(expr.Substring(p, p - match.Index), @"^([+ ])+|([+ ])+$", string.Empty, RegexOptions.Compiled));
                layout.Blocks.Add(tlb);
              }

              tlb = (TextLayoutBlock)textBlock.Clone();
              tlb.TextExpression = ReplaceQuotes(match.Groups["text"].Value);
              string formatProps = match.Groups["args"].Value;
              if (!string.IsNullOrEmpty(formatProps))
              {
                // We apply format properties
                MatchCollection matchArgs = Regex.Matches(formatProps, @"(?<args>[0-9a-zA-Z-]*=\s*('|"").*?('|""))", RegexOptions.Compiled | RegexOptions.ExplicitCapture);
                for (int j = 0; j < matchArgs.Count; j++)
                {
                  Match matchKeyValue = Regex.Match(matchArgs[j].Value, @"((?<key>[0-9a-zA-Z-]*)=(?<value>\s*('|"").*?('|"")))", RegexOptions.Compiled);
                  string key = matchKeyValue.Groups["key"].Value;

                  if (string.IsNullOrEmpty(key))
                    continue;

                  string value = RemoveQuotes(matchKeyValue.Groups["value"].Value);

                  switch (key.ToLower())
                  {
                    case "fill":
                      tlb.TextFormat.TextStyle.Color = ColorUtility.FromHtml(value);
                      break;
                    case "size":
                      tlb.TextFormat.TextStyle.Font.Size = Convert.ToSingle(value);
                      break;
                    case "face-name":
                      SetFontName(tlb, value);
                      break;
                  }
                }
              }

              layout.Blocks.Add(tlb);

              p = match.Index + match.Length;
            }

            if (p < expr.Length)
            {
              tlb = (TextLayoutBlock)textBlock.Clone();
              tlb.TextExpression = ReplaceQuotes(Regex.Replace(expr.Substring(p, expr.Length - p), @"^([+ ])+|([+ ])+$", string.Empty, RegexOptions.Compiled));
              layout.Blocks.Add(tlb);
            }
          }
        }
      }
    }
 public void UpdateEditingLayout(TextLayout layout)
 {
     EditLayout = layout;
 }
Example #50
0
 public abstract void DrawTextLayout(object backend, TextLayout layout, double x, double y);
Example #51
0
 public float MeasureString(string text, TextFormat font)
 {
     using (TextLayout layout = new TextLayout(directWriteFactory, text, font, 1000, 1000))
         return((float)layout.Metrics.WidthIncludingTrailingWhitespace);
 }
Example #52
0
 protected override void DoApply(TextLayout layout, TextRange range)
 {
     layout.SetFontSize(this.Size, range);
 }
Example #53
0
    /**
     * Adjust the size of the TextShape so it encompasses the text inside it.
     *
     * @return a <code>Rectangle2D</code> that is the bounds of this <code>TextShape</code>.
     */
    public Rectangle2D resizeToFitText(){
        String txt = GetText();
        if(txt == null || txt.Length == 0) return new Rectangle2D.Float();

        RichTextRun rt = GetTextRun().GetRichTextRuns()[0];
        int size = rt.GetFontSize();
        int style = 0;
        if (rt.IsBold()) style |= Font.BOLD;
        if (rt.IsItalic()) style |= Font.ITALIC;
        String fntname = rt.GetFontName();
        Font font = new Font(fntname, style, size);

        float width = 0, height = 0, leading = 0;
        String[] lines = txt.split("\n");
        for (int i = 0; i < lines.Length; i++) {
            if(lines[i].Length == 0) continue;

            TextLayout layout = new TextLayout(lines[i], font, _frc);

            leading = Math.max(leading, layout.GetLeading());
            width = Math.max(width, layout.GetAdvance());
            height = Math.max(height, (height + (layout.GetDescent() + layout.GetAscent())));
        }

        // add one character to width
        Rectangle2D charBounds = font.GetMaxCharBounds(_frc);
        width += GetMarginLeft() + GetMarginRight() + charBounds.Width;

        // add leading to height
        height += GetMarginTop() + GetMarginBottom() + leading;

        Rectangle2D anchor = GetAnchor2D();
        anchor.SetRect(anchor.GetX(), anchor.GetY(), width, height);
        SetAnchor(anchor);

        return anchor;
    }
Example #54
0
 protected override void DoApply(TextLayout layout, TextRange range)
 {
     layout.SetStrikethrough(true, range);
 }
Example #55
0
        public new void 描画する(Matrix ワールド行列変換, RectangleF?レイアウト矩形 = null)
        {
            Debug.Assert(this.活性化している);

            if (this.タイトル.Nullまたは空である())
            {
                return;
            }

            var 全体矩形 = レイアウト矩形 ?? new RectangleF(0f, 0f, this.サイズ.Width, this.サイズ.Height);

            var マージン     = 4f;
            var タイトル文字矩形 = new RectangleF(全体矩形.X + マージン, 全体矩形.Y + マージン, 全体矩形.Width - マージン * 2f, 全体矩形.Height - マージン * 2f);

            // タイトルまたはサブタイトルが変更されているなら、ここでビットマップの更新を行う。
            if (!(string.Equals(this.タイトル, this._前回のタイトル)) ||
                !(string.Equals(this.サブタイトル, this._前回のサブタイトル)))
            {
                this._前回のタイトル   = this.タイトル;
                this._前回のサブタイトル = this.サブタイトル;

                using (var タイトルレイアウト = new TextLayout(
                           グラフィックデバイス.Instance.DWriteFactory,
                           this.タイトル,
                           this._textFormat,
                           タイトル文字矩形.Width,
                           タイトル文字矩形.Height))
                {
                    var タイトルサイズ = new Size2F(
                        タイトルレイアウト.Metrics.WidthIncludingTrailingWhitespace,
                        タイトルレイアウト.Metrics.Height);

                    var サブタイトル文字矩形 = タイトル文字矩形;
                    サブタイトル文字矩形.Y += タイトルサイズ.Height; // サブタイトルの位置は、タイトルの縦幅分だけ下へ移動。

                    using (var サブタイトルレイアウト = new TextLayout(
                               グラフィックデバイス.Instance.DWriteFactory,
                               this.サブタイトル,
                               this._textFormat,
                               サブタイトル文字矩形.Width,
                               サブタイトル文字矩形.Height))
                    {
                        this.テクスチャへ描画する((dct) => {
                            // dc は最終的に bmp をテクスチャに描画するので、DPX to DPX 。
                            dct.Transform = Matrix3x2.Identity;

                            // 背景色で塗りつぶす。
                            dct.FillRectangle(全体矩形, this._backBrush);

                            // タイトルを描画。
                            dct.DrawTextLayout(
                                new Vector2(タイトル文字矩形.X, タイトル文字矩形.Y),
                                タイトルレイアウト,
                                this._titleFontBrush,
                                DrawTextOptions.Clip);

                            // サブタイトルを描画。
                            dct.DrawTextLayout(
                                new Vector2(サブタイトル文字矩形.X, サブタイトル文字矩形.Y),
                                サブタイトルレイアウト,
                                this._subtitleFontBrush,
                                DrawTextOptions.Clip);
                        });
                    }
                }
            }

            // テクスチャを描画する。
            base.描画する(ワールド行列変換);
        }
        /// <summary>
        /// Draws the text.
        /// </summary>
        /// <param name="p">The position.</param>
        /// <param name="text">The text.</param>
        /// <param name="fill">The fill color.</param>
        /// <param name="fontFamily">The font family.</param>
        /// <param name="fontSize">Size of the font.</param>
        /// <param name="fontWeight">The font weight.</param>
        /// <param name="rotate">The rotation angle.</param>
        /// <param name="halign">The horizontal alignment.</param>
        /// <param name="valign">The vertical alignment.</param>
        /// <param name="maxSize">The maximum size of the text.</param>
        public void DrawText(
            ScreenPoint p,
            string text,
            OxyColor fill,
            string fontFamily,
            double fontSize,
            double fontWeight,
            double rotate,
            OxyPlot.HorizontalAlignment halign,
            OxyPlot.VerticalAlignment valign,
            OxySize? maxSize)
        {
            if (string.IsNullOrWhiteSpace(fontFamily))
            {
                fontFamily = "Arial";
            }

            if (text == null)
            {
                text = string.Empty;
            }

            var format = new TextFormat(this.dwtFactory, fontFamily, GetFontWeight(fontWeight), FontStyle.Normal, FontStretch.Normal, (float)fontSize);
            var maxWidth = 1000f;
            var maxHeight = 1000f;
            if (maxSize != null)
            {
                maxHeight = (float)maxSize.Value.Height;
                maxWidth = (float)maxSize.Value.Width;
            }

            var layout = new TextLayout(this.dwtFactory, text, format, maxWidth, maxHeight);

            var size = new Size2F(layout.Metrics.Width, layout.Metrics.Height);
            if (maxSize != null)
            {
                if (size.Width > maxSize.Value.Width)
                {
                    size.Width = (float)maxSize.Value.Width;
                }

                if (size.Height > maxSize.Value.Height)
                {
                    size.Height = (float)maxSize.Value.Height;
                }
            }

            float dx = 0;
            if (halign == OxyPlot.HorizontalAlignment.Center)
            {
                dx = -size.Width / 2;
            }

            if (halign == OxyPlot.HorizontalAlignment.Right)
            {
                dx = -size.Width;
            }

            float dy = 0;
            if (valign == OxyPlot.VerticalAlignment.Middle)
            {
                dy = -size.Height / 2;
            }

            if (valign == OxyPlot.VerticalAlignment.Bottom)
            {
                dy = -size.Height;
            }

            this.renderUnits.Add(new TextRenderUnit(layout, this.GetBrush(fill), Matrix3x2.Translation(dx, dy) * Matrix3x2.Rotation((float)rotate) * Matrix3x2.Translation(p.ToVector2())));
            format.Dispose();
        }
Example #57
0
        private void DrawLegend()
        {
            if (_legendFont == null || _legendFont.IsDisposed)
            {
                _legendFont = Surface.Fonts.GetTextFormat(MM_Repository.OverallDisplay.NetworkMapFont);
            }

            Vector2 start = new Vector2(30, 30 + MM_Repository.KVLevels.Count * 20 + 10);
            Vector2 end   = start + new Vector2(235, 125);

            Surface.RenderTarget2D.FillRectangle(new RawRectangleF(start.X - 10, start.Y - 10, end.X + 20, end.Y + 10), Surface.Brushes.GetBrush(new Color4(0, 0, 0, 0.5f)));

            var position   = start + new Vector2(20, 5);
            var offset     = new Vector2(50, 0);
            var textOffset = new Vector2(0, 15);
            var whiteBrush = Surface.Brushes.GetBrush(Color4.White);

            foreach (var fuelColor in SubstationLayer.FuelColors)
            {
                if (position.X > end.X)
                {
                    position.X  = start.X + 20;
                    position.Y += textOffset.Y * 3;
                }

                var brush = Surface.Brushes.GetBrush(fuelColor.Value, 0.6f);

                if (fuelColor.Key == "LOAD")
                {
                    Surface.RenderTarget2D.FillRectangle(new RectangleF(position.X - 7.5f, position.Y - 7.5f, 15, 15), brush);
                }
                else
                {
                    Surface.RenderTarget2D.FillEllipse(new Ellipse(position, 10, 10), brush);
                }
                using (var layout = new TextLayout(Surface.FactoryDirectWrite, fuelColor.Key, _legendFont, offset.X, 14))
                {
                    var textLoc = position + textOffset;
                    Surface.RenderTarget2D.DrawTextAtPoint(layout, whiteBrush, textLoc.X, textLoc.Y, centerX: true, options: DrawTextOptions.Clip);
                    position += offset;
                }
            }

            var onlineBrush = Surface.Brushes.GetBrush(SubstationLayer.FuelColors["WIND"], 0.6f);

            var tx = Surface.RenderTarget2D.Transform;

            Surface.RenderTarget2D.Transform = Matrix3x2.Translation(position);
            if (_slice != null && !_slice.IsDisposed)
            {
                Surface.RenderTarget2D.FillGeometry(_slice, onlineBrush);
            }
            Surface.RenderTarget2D.Transform = tx;

            Surface.RenderTarget2D.DrawEllipse(new Ellipse(position, 10, 10), onlineBrush);
            using (var layout = new TextLayout(Surface.FactoryDirectWrite, "MW & Max", _legendFont, offset.X, 14))
            {
                var textLoc = position + textOffset;
                Surface.RenderTarget2D.DrawTextAtPoint(layout, whiteBrush, textLoc.X, textLoc.Y, centerX: true, options: DrawTextOptions.Clip);
            }

            position += offset;
            if (position.X > end.X)
            {
                position.X  = start.X + 20;
                position.Y += textOffset.Y * 3;
            }

            Surface.RenderTarget2D.DrawEllipse(new Ellipse(position, 10, 10), onlineBrush, 2f, _dashStyle);
            using (var layout = new TextLayout(Surface.FactoryDirectWrite, "Offline", _legendFont, offset.X, 14))
            {
                var textLoc = position + textOffset;
                Surface.RenderTarget2D.DrawTextAtPoint(layout, whiteBrush, textLoc.X, textLoc.Y, centerX: true, options: DrawTextOptions.Clip);
            }

            position += offset;
            if (position.X > end.X)
            {
                position.X  = start.X + 20;
                position.Y += textOffset.Y * 3;
            }

            using (var layout = new TextLayout(Surface.FactoryDirectWrite, "Unit", _legendFont, offset.X, 14))
                using (var geom = SharpDxExtensions.CreatePathGeometry(Surface.Factory2D, true, true,
                                                                       new Vector2(position.X - 5, position.Y),
                                                                       new Vector2(position.X, position.Y - 5),
                                                                       new Vector2(position.X + 5, position.Y),
                                                                       new Vector2(position.X, position.Y + 5)))
                {
                    Surface.RenderTarget2D.FillGeometry(geom, whiteBrush);

                    var textLoc = position + textOffset;
                    Surface.RenderTarget2D.DrawTextAtPoint(layout, whiteBrush, textLoc.X, textLoc.Y, centerX: true, options: DrawTextOptions.Clip);
                }

            position += offset;
            if (position.X > end.X)
            {
                position.X  = start.X + 20;
                position.Y += textOffset.Y * 3;
            }

            Surface.RenderTarget2D.FillRectangle(new RectangleF(position.X - 2, position.Y - 2, 2 * 2f, 2 * 2f), whiteBrush);
            using (var layout = new TextLayout(Surface.FactoryDirectWrite, "Substation", _legendFont, offset.X, 14))
            {
                var textLoc = position + textOffset;
                Surface.RenderTarget2D.DrawTextAtPoint(layout, whiteBrush, textLoc.X, textLoc.Y, centerX: true, options: DrawTextOptions.Clip);
            }
        }
        /// <summary>
        /// Measures the text.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="fontFamily">The font family.</param>
        /// <param name="fontSize">Size of the font.</param>
        /// <param name="fontWeight">The font weight.</param>
        /// <returns>The text size.</returns>
        public OxySize MeasureText(string text, string fontFamily, double fontSize, double fontWeight)
        {
            if (string.IsNullOrWhiteSpace(fontFamily))
            {
                fontFamily = "Arial";
            }

            if (text == null)
            {
                text = string.Empty;
            }

            var format = new TextFormat(this.dwtFactory, fontFamily, GetFontWeight(fontWeight), FontStyle.Normal, FontStretch.Normal, (float)fontSize);

            var layout = new TextLayout(this.dwtFactory, text, format, 1000f, 1000f);
            var res = new OxySize(layout.Metrics.Width, layout.Metrics.Height);

            format.Dispose();
            layout.Dispose();

            return res;
        }
Example #59
0
        public virtual void Texts(Xwt.Drawing.Context ctx, double x, double y)
        {
            ctx.Save();

            ctx.Translate(x, y);

            ctx.SetColor(Colors.Black);

            var col1 = new Rectangle();
            var col2 = new Rectangle();

            var text = new TextLayout();

            text.Font = this.Font.WithSize(24);
            Console.WriteLine(text.Font.Size);

            // first text
            text.Text = "Lorem ipsum dolor sit amet,";
            var size1 = text.GetSize();

            col1.Width   = size1.Width;
            col1.Height += size1.Height + 10;
            ctx.DrawTextLayout(text, 0, 0);


            // proofing width; test should align with text above
            ctx.SetColor(Colors.DarkMagenta);
            text.Text  = "consetetur sadipscing elitr, sed diam nonumy";
            text.Width = col1.Width;
            var size2 = text.GetSize();

            ctx.DrawTextLayout(text, 0, col1.Bottom);
            col1.Height += size2.Height + 10;

            ctx.SetColor(Colors.Black);

            // proofing scale, on second col
            ctx.Save();
            ctx.SetColor(Colors.Red);
            col2.Left = col1.Right + 10;

            text.Text = "eirmod tempor invidunt ut.";

            var scale = 1.2;

            text.Width = text.Width / scale;
            var size3 = text.GetSize();

            col2.Height = size3.Height * scale;
            col2.Width  = size3.Width * scale + 5;
            ctx.Scale(scale, scale);
            ctx.DrawTextLayout(text, col2.Left / scale, col2.Top / scale);
            ctx.Restore();

            // proofing heigth, on second col
            ctx.Save();
            ctx.SetColor(Colors.DarkCyan);
            text.Text = "Praesent ac lacus nec dolor pulvinar feugiat a id elit.";
            var size4 = text.GetSize();

            text.Height   = size4.Height / 2;
            text.Trimming = TextTrimming.WordElipsis;
            ctx.DrawTextLayout(text, col2.Left, col2.Bottom + 5);

            ctx.SetLineWidth(1);
            ctx.SetColor(Colors.Blue);
            ctx.Rectangle(new Rectangle(col2.Left, col2.Bottom + 5, text.Width, text.Height));
            ctx.Stroke();
            ctx.Restore();

            // drawing col line
            ctx.SetLineWidth(1);

            ctx.SetColor(Colors.Black.WithAlpha(.5));
            ctx.MoveTo(col1.Right + 5, col1.Top);
            ctx.LineTo(col1.Right + 5, col1.Bottom);
            ctx.Stroke();
            ctx.MoveTo(col2.Right + 5, col2.Top);
            ctx.LineTo(col2.Right + 5, col2.Bottom);
            ctx.Stroke();
            ctx.SetColor(Colors.Black);

            // proofing rotate, and printing size to see the values
            ctx.Save();

            text.Font = this.Font.WithSize(10);
            text.Text = string.Format("Size 1 {0}\r\nSize 2 {1}\r\nSize 3 {2} Scale {3}",
                                      size1, size2, size3, scale);
            text.Width  = -1;            // this clears textsize
            text.Height = -1;
            ctx.Rotate(5);
            // maybe someone knows a formula with angle and textsize to calculyte ty
            var ty = 30;

            ctx.DrawTextLayout(text, ty, col1.Bottom + 10);

            ctx.Restore();

            // scale example here:

            ctx.Restore();

            TextLayout tl0 = new TextLayout(this);

            tl0.Font = this.Font.WithSize(10);
            tl0.Text = "This text contains attributes.";
            tl0.SetUnderline(0, "This".Length);
            tl0.SetForeground(new Color(0, 1.0, 1.0), "This ".Length, "text".Length);
            tl0.SetBackground(new Color(0, 0, 0), "This ".Length, "text".Length);
            tl0.SetFontWeight(FontWeight.Bold, "This text ".Length, "contains".Length);
            tl0.SetFontStyle(FontStyle.Italic, "This text ".Length, "contains".Length);
            tl0.SetStrikethrough("This text contains ".Length, "attributes".Length);

            ctx.DrawTextLayout(tl0, col2.Left, col2.Bottom + 100);


            // Text boces

            y = 180;

            // Without wrapping

            TextLayout tl = new TextLayout(this);

            tl.Text = "Stright text";
            DrawText(ctx, tl, ref y);

            // With wrapping

            tl       = new TextLayout(this);
            tl.Text  = "The quick brown fox jumps over the lazy dog";
            tl.Width = 100;
            DrawText(ctx, tl, ref y);

            // With blank lines

            tl       = new TextLayout(this);
            tl.Text  = "\nEmpty line above\nLine break above\n\nEmpty line above\n\n\nTwo empty lines above\nEmpty line below\n";
            tl.Width = 200;
            DrawText(ctx, tl, ref y);
        }
Example #60
0
    /**
     * Renders the text specified by the specified <code>String</code>,
     * using the current text attribute state in the <code>Graphics2D</code> context.
     * The baseline of the first character is at position
     * (<i>x</i>,&nbsp;<i>y</i>) in the User Space.
     * The rendering attributes applied include the <code>Clip</code>,
     * <code>Transform</code>, <code>Paint</code>, <code>Font</code> and
     * <code>Composite</code> attributes. For characters in script systems
     * such as Hebrew and Arabic, the glyphs can be rendered from right to
     * left, in which case the coordinate supplied is the location of the
     * leftmost character on the baseline.
     * @param s the <code>String</code> to be rendered
     * @param x the x coordinate of the location where the
     * <code>String</code> should be rendered
     * @param y the y coordinate of the location where the
     * <code>String</code> should be rendered
     * @throws NullPointerException if <code>str</code> is
     *         <code>null</code>
     * @see #setPaint
     * @see java.awt.Graphics#setColor
     * @see java.awt.Graphics#setFont
     * @see #setTransform
     * @see #setComposite
     * @see #setClip
     */
    public void DrawString(String s, float x, float y) {
        TextBox txt = new TextBox(_group);
        txt.GetTextRun().supplySlideShow(_group.Sheet.GetSlideShow());
        txt.GetTextRun().SetSheet(_group.Sheet);
        txt.SetText(s);

        RichTextRun rt = txt.GetTextRun().GetRichTextRuns()[0];
        rt.SetFontSize(_font.GetSize());
        rt.SetFontName(_font.GetFamily());

        if (getColor() != null) rt.SetFontColor(getColor());
        if (_font.IsBold()) rt.SetBold(true);
        if (_font.IsItalic()) rt.SetItalic(true);

        txt.SetMarginBottom(0);
        txt.SetMarginTop(0);
        txt.SetMarginLeft(0);
        txt.SetMarginRight(0);
        txt.SetWordWrap(TextBox.WrapNone);
        txt.SetHorizontalAlignment(TextBox.AlignLeft);
        txt.SetVerticalAlignment(TextBox.AnchorMiddle);


        TextLayout layout = new TextLayout(s, _font, GetFontRenderContext());
        float ascent = layout.GetAscent();

        float width = (float) Math.floor(layout.GetAdvance());
        /**
         * Even if top and bottom margins are Set to 0 PowerPoint
         * always Sets extra space between the text and its bounding box.
         *
         * The approximation height = ascent*2 works good enough in most cases
         */
        float height = ascent * 2;

        /*
          In powerpoint anchor of a shape is its top left corner.
          Java graphics Sets string coordinates by the baseline of the first character
          so we need to shift up by the height of the textbox
        */
        y -= height / 2 + ascent / 2;

        /*
          In powerpoint anchor of a shape is its top left corner.
          Java graphics Sets string coordinates by the baseline of the first character
          so we need to shift down by the height of the textbox
        */
        txt.SetAnchor(new Rectangle2D.Float(x, y, width, height));

        _group.AddShape(txt);
    }