public FormattedTextImpl(string text, string fontFamilyName, double fontSize, FontStyle fontStyle,
                    TextAlignment textAlignment, FontWeight fontWeight, TextWrapping wrapping)
        {
            _text = text ?? string.Empty;

            // Replace 0 characters with zero-width spaces (200B)
            _text = _text.Replace((char)0, (char)0x200B);

            var typeface = TypefaceCache.GetTypeface(fontFamilyName, fontStyle, fontWeight);

            _paint = new SKPaint();

            //currently Skia does not measure properly with Utf8 !!!
            //Paint.TextEncoding = SKTextEncoding.Utf8;
            _paint.TextEncoding = SKTextEncoding.Utf16;
            _paint.IsStroke = false;
            _paint.IsAntialias = true;            
            _paint.LcdRenderText = true;            
            _paint.SubpixelText = true;
            _paint.Typeface = typeface;
            _paint.TextSize = (float)fontSize;
            _paint.TextAlign = textAlignment.ToSKTextAlign();

            _wrapping = wrapping;

            Rebuild();
        }
 public FixedWidthColumn(string name, int width, TextAlignment align, char blankChar)
 {
     this._name = name;
     this._w = width;
     this._align = align;
     this._blank = blankChar;
 }
        public FormattedTextImpl(
            string text,
            string fontFamily,
            double fontSize,
            FontStyle fontStyle,
            TextAlignment textAlignment,
            FontWeight fontWeight,
            TextWrapping wrapping)
        {
            var factory = AvaloniaLocator.Current.GetService<DWrite.Factory>();

            using (var format = new DWrite.TextFormat(
                factory,
                fontFamily,
                (DWrite.FontWeight)fontWeight,
                (DWrite.FontStyle)fontStyle,
                (float)fontSize))
            {
                format.WordWrapping = wrapping == TextWrapping.Wrap ? 
                    DWrite.WordWrapping.Wrap : DWrite.WordWrapping.NoWrap;

                TextLayout = new DWrite.TextLayout(
                    factory,
                    text ?? string.Empty,
                    format,
                    float.MaxValue,
                    float.MaxValue);
            }

            TextLayout.TextAlignment = textAlignment.ToDirect2D();
        }
Beispiel #4
0
 public GUIButton(int x, int y, int width, int height)
     : base(x, y, width, height)
 {
     _text = "New Button";
     _clickAction = GUIClickAction.RunScript;
     _textAlign = TextAlignment.TopMiddle;
 }
        public static FormattedText Create(string text, Font font, TextAlignment alignment, SizeConstraint constraint)
        {
            if (text == null)
            {
                return new FormattedText(null, new Box2(0, 0, 0, 0), text, font, alignment, constraint);
            }
            else
            {
                var instances = new List<GlyphInstance>(text.Length);
                var x = 0f;

                foreach (var c in text)
                {
                    var glyph = font.GetGlyph(c);

                    if (glyph != null)
                    {
                        instances.Add(new GlyphInstance(new Box2(x, 0, glyph.Size.X, glyph.Size.Y), glyph.Sprite));
                        x += glyph.Size.X;
                    }
                }

                return new FormattedText(instances, new Box2(0, 0, x, font.Height), text, font, alignment, constraint);
            }
        }
Beispiel #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FormattedText"/> class.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="fontFamilyName">The font family.</param>
        /// <param name="fontSize">The font size.</param>
        /// <param name="fontStyle">The font style.</param>
        /// <param name="textAlignment">The text alignment.</param>
        /// <param name="fontWeight">The font weight.</param>
        public FormattedText(
            string text,
            string fontFamilyName,
            double fontSize,
            FontStyle fontStyle,
            TextAlignment textAlignment,
            FontWeight fontWeight)
        {
            //TODO: Find out why it was null in the first place. Demo project - AvalonStudio
            //https://github.com/VitalElement/AvalonStudio/commit/787fb9396feb74e6ca6bd4e08436269a349df9c6
            text = text ?? "";
            Text = text;
            FontFamilyName = fontFamilyName;
            FontSize = fontSize;
            FontStyle = fontStyle;
            FontWeight = fontWeight;
            TextAlignment = textAlignment;

            var platform = PerspexLocator.Current.GetService<IPlatformRenderInterface>();

            PlatformImpl = platform.CreateFormattedText(
                text,
                fontFamilyName,
                fontSize,
                fontStyle,
                textAlignment,
                fontWeight);
        }
Beispiel #7
0
 public SignalChooser(INodeWrapper nodeItem, NodeSignalIn initialSignalIn, double maxWidth, TextAlignment textAlignment)
 {
     NodeItem = nodeItem;
     SignalIn = initialSignalIn;
     MaxWidth = maxWidth;
     TextAlignment = textAlignment;
 }
		public static void UpdateFromFormsControl (this UILabel uiLabel, string text, TextAlignment textAlignment, Color textColor, Font font)
		{
			uiLabel.Text = text;
			uiLabel.TextAlignment = textAlignment.ToUITextAlignment ();
			uiLabel.TextColor = textColor.ToUIColor ();
			uiLabel.Font = font.ToUIFont ();
		}
 public LabelTextureButton(
     Screen screen,
     SpriteBatch spriteBatch,
     UIAlignment alignment,
     int x,
     int y,
     Texture2D selectedTexture,
     Texture2D deselectedTexture,
     Rectangle localHitBox,
     SpriteFont font,
     TextAlignment textAlignment,
     string text,
     int textXOffset,
     int textYOffset,
     int outline,
     Color selectedColor,
     Color deselectedColor,
     Action onActivate,
     Action onMouseOver,
     Action onMouseOut)
     : base(screen, spriteBatch, alignment, x, y, selectedTexture, deselectedTexture, localHitBox, onActivate, onMouseOver, onMouseOut)
 {
     _font = font;
     _textAlignment = textAlignment;
     _text = text;
     _textXOffset = textXOffset;
     _textYOffset = textYOffset;
     _outline = outline;
     _selectedColor = selectedColor;
     _deselectedColor = deselectedColor;
 }
 public GestureOptionEntry(string text, Texture2D icon, Vector2 iconSize, Vector2 position, float scale, Color color, TextAlignment alignment, GestureTest test, GestureHandler callback)
     : base(text, icon, iconSize, position, scale, color, alignment)
 {
     unlockedColor = color;
     this.callback = callback;
     this.test = test;
 }
 public static void UpdateFromFormsControl(this TextView textView, string text, Color formsColor, Font formsFont, TextAlignment textAlignment)
 {
     textView.Text = text;
     textView.SetTextColor(formsColor.ToAndroid(Color.Default));
     textView.UpdateFont(formsFont);
     textView.Gravity = textAlignment.ToNative();
 }
Beispiel #12
0
        //    http://stackoverflow.com/questions/14932063/convert-code-of-a-user-control-from-vb-net-to-c-sharp
        //https://mightycoco.wordpress.com/2009/09/22/getstringformatfromcontentallignment-converting-contentallignment-data-into-stringformat-data/
        public static StringFormat BuildStringFormat(StringTrimming stringTrimming,TextAlignment alignment)
        {
            StringFormat format = StringFormat.GenericTypographic;
            format.Trimming = stringTrimming;
            format.FormatFlags = StringFormatFlags.LineLimit;
            switch (alignment) {
                    case TextAlignment.Left:{
                        format.Alignment = StringAlignment.Near;
                        format.LineAlignment = StringAlignment.Near;
                        return format;
                    }
                    case TextAlignment.Center:{
                        format.Alignment = StringAlignment.Center;
                        format.LineAlignment = StringAlignment.Near;
                        return format;
                    }

                    case TextAlignment.Right:{
                        format.Alignment = StringAlignment.Far;
                        format.LineAlignment = StringAlignment.Near;
                        return format;
                    }

                    case TextAlignment.Justify:{
                        format.Alignment = StringAlignment.Center;
                        format.LineAlignment = StringAlignment.Near;
                        return format;
                    }
            }
            return format;
        }
        public FormattedTextImpl(
            Pango.Context context,
            string text,
            string fontFamily,
            double fontSize,
            FontStyle fontStyle,
            TextAlignment textAlignment,
            FontWeight fontWeight)
        {
            Contract.Requires<ArgumentNullException>(context != null);
            Contract.Requires<ArgumentNullException>(text != null);
            Layout = new Pango.Layout(context);
            _text = text;
            Layout.SetText(text);
            Layout.FontDescription = new Pango.FontDescription
            {
                Family = fontFamily,
                Size = Pango.Units.FromDouble(CorrectScale(fontSize)),
                Style = (Pango.Style)fontStyle,
                Weight = fontWeight.ToCairo()
            };

            Layout.Alignment = textAlignment.ToCairo();
            Layout.Attributes = new Pango.AttrList();
        }
Beispiel #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FormattedText"/> class.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="fontFamilyName">The font family.</param>
        /// <param name="fontSize">The font size.</param>
        /// <param name="fontStyle">The font style.</param>
        /// <param name="textAlignment">The text alignment.</param>
        /// <param name="fontWeight">The font weight.</param>
        public FormattedText(
            string text,
            string fontFamilyName,
            double fontSize,
            FontStyle fontStyle,
            TextAlignment textAlignment,
            FontWeight fontWeight)
        {
            Contract.Requires<ArgumentNullException>(text != null);
            Contract.Requires<ArgumentNullException>(fontFamilyName != null);
            Contract.Requires<ArgumentException>(fontSize > 0);

            Text = text;
            FontFamilyName = fontFamilyName;
            FontSize = fontSize;
            FontStyle = fontStyle;
            FontWeight = fontWeight;
            TextAlignment = textAlignment;

            var platform = PerspexLocator.Current.GetService<IPlatformRenderInterface>();

            if (platform == null)
            {
                throw new Exception("Could not create FormattedText: IPlatformRenderInterface not registered.");
            }

            PlatformImpl = platform.CreateFormattedText(
                text,
                fontFamilyName,
                fontSize,
                fontStyle,
                textAlignment,
                fontWeight);
        }
Beispiel #15
0
 public Text(string text, TextAlignment align, int x, int y)
 {
     Label = text;
     Align = align;
     X = x;
     Y = y;
 }
Beispiel #16
0
        public FormattedTextImpl(
            string text,
            string fontFamily,
            double fontSize,
            FontStyle fontStyle,
            TextAlignment textAlignment,
            FontWeight fontWeight)
        {
            var factory = Locator.Current.GetService<DWrite.Factory>();

            var format = new DWrite.TextFormat(
                factory,
                fontFamily,
                (DWrite.FontWeight)fontWeight,
                (DWrite.FontStyle)fontStyle,
                (float)fontSize);

            TextLayout = new DWrite.TextLayout(
                factory,
                text ?? string.Empty,
                format,
                float.MaxValue,
                float.MaxValue);

            TextLayout.TextAlignment = textAlignment.ToDirect2D();
        }
 public TextComponent(string myText, TextAlignment myAlignment, Vector2 myPosition, SpriteFont myFont)
 {
     Destination = myPosition;
     textAlighment = myAlignment;
     font = myFont;
     text = myText;
 }
Beispiel #18
0
    public static GameObject ShowText(string name, string text, float time, TextAlignment alignment, TextAnchor anchor, float x, float y)
    {
        LoadFonts();

        // Destroy old object if existent
        GameObject textObject = GameObject.Find(PREFIX + name);
        MonoBehaviour.Destroy(textObject);

        textObject = new GameObject(PREFIX + name);

        textObject.AddComponent<OutlineText>().thickness = 2;

        TutorialText textBehaviour = textObject.GetComponent<TutorialText>();

        if (textBehaviour == null)
            textBehaviour = textObject.AddComponent<TutorialText>();

        GUIScale textScaler = textObject.GetComponent<GUIScale>();
        GUIText guitext = textObject.guiText;
        guitext.enabled = true;

        textObject.transform.position = new Vector3(x, y, 0);

        guitext.text = text;
        guitext.anchor = anchor;
        guitext.alignment = alignment;
        //guitext.font = bigFont;
        //guitext.material = bigMat;
        //guitext.fontSize = 48;

        if (time > 0)
            textBehaviour.DestroyIn(time);

        return textObject;
    }
Beispiel #19
0
        public FormattedText(
            string text,
            string fontFamilyName,
            double fontSize,
            FontStyle fontStyle,
            TextAlignment textAlignment,
            FontWeight fontWeight)
        {
            this.Text = text;
            this.FontFamilyName = fontFamilyName;
            this.FontSize = fontSize;
            this.FontStyle = fontStyle;
            this.FontWeight = fontWeight;
            this.TextAlignment = textAlignment;

            var platform = Locator.Current.GetService<IPlatformRenderInterface>();

            this.PlatformImpl = platform.CreateFormattedText(
                text,
                fontFamilyName,
                fontSize,
                fontStyle,
                textAlignment,
                fontWeight);
        }
Beispiel #20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TextLine"/> class.
 /// </summary>
 /// <param name="font">The font used to display text in this textline.</param>
 public TextLine(FontInfo font)
     : base(Vector2D.Zero, Vector2D.Zero)
 {
     this.text = string.Empty;
     this.font = font;
     this.color = Color.Black;
     this.alignment = TextAlignment.Left;
 }
Beispiel #21
0
		public Text (string text, Rect frame, Font font, TextAlignment alignment = TextAlignment.Left, Pen pen = null, Brush brush = null)
			: base (pen, brush)
		{
			Frame = frame;
			Font = font;
			Alignment = alignment;
			Spans = new List<TextSpan> { new TextSpan (text) };
		}
Beispiel #22
0
		public Text (Rect frame, Font font, TextAlignment alignment = TextAlignment.Left, Pen pen = null, Brush brush = null)
			: base (pen, brush)
		{
			Frame = frame;
			Font = font;
			Alignment = alignment;
			Spans = new List<TextSpan> ();
		}
Beispiel #23
0
 public Text(string text, Rect frame, Font font, TextAlignment alignment = TextAlignment.Left, Pen pen = null, BaseBrush brush = null)
     : base(pen, brush)
 {
     String = text;
     Frame = frame;
     Font = font;
     Alignment = alignment;
 }
 public TableColumnDefinition(string title, string format, int width, TextAlignment textAlignment, OverflowBehavior overflowBehavior)
 {
     Title = title;
     Format = format;
     Width = width;
     TextAlignment = textAlignment;
     OverflowBehavior = overflowBehavior;
 }
Beispiel #25
0
 public Text(ComponentPoint location, TextAlignment alignment, double size, string text)
 {
     Location = location;
     Alignment = alignment;
     var textRun = new TextRun(text, new TextRunFormatting(TextRunFormattingType.Normal, size));
     TextRuns = new List<TextRun>();
     TextRuns.Add(textRun);
 }
Beispiel #26
0
 public SignalValue(INodeWrapper nodeItem, NodeSignal initialSignal, double maxWidth, TextAlignment textAlignment, string formatString)
 {
     Signal = initialSignal;
     NodeItem = nodeItem;
     MaxWidth = maxWidth;
     TextAlignment = textAlignment;
     FormatString = formatString;
 }
        public IconText(string t, Texture2D iconSprite, Vector2 iconSize, Vector2 position, float scale, Color color, TextAlignment alignment, TextEffect effect = TextEffect.None, float alpha = 1.0f)
            : base(position,new Vector2(0,-1),Vector2.Zero)
        {
            text = new Text(t,  position, scale, color, effect);
            icon = new DrawableAsset<Texture2D>(Vector2.Zero, new Vector2(0, -1), iconSize, iconSprite);

            this.alignment = alignment;
            UpdateAlignment();
        }
 private FormattedText(List<GlyphInstance> instances, Box2 bounds, string text, Font font, TextAlignment alignment, SizeConstraint constraint)
 {
     m_instances = instances;
     Bounds = bounds;
     Text = text;
     Font = font;
     Alignment = alignment;
     Constraint = constraint;
 }
Beispiel #29
0
 public void Reply(bool allowed, int code, string message, TextAlignment alignment = TextAlignment.Left)
 {
     var task = ReplyAsync(allowed, code, message, alignment);
     task.Wait();
     if (task.IsFaulted && task.Exception != null)
     {
         throw task.Exception;
     }
 }
Beispiel #30
0
 public FontRendering()
 {
     _fontSize = 12.0f;
     _alignment = TextAlignment.Left;
     _textDecorations = new TextDecorationCollection();
     _textColor = Brushes.Black;
     _typeface = new Typeface(new FontFamily("Arial"),
        FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
 }
        /// <summary>
        /// Creates and return a textblock tailored to your arguments
        /// </summary>
        /// <param name="text">What text should the textblock display</param>
        /// <param name="name">What name does the textblock have</param>
        /// <param name="fontsize">What fontsize does the text have</param>
        /// <param name="textAlignment">What alignment does the text have</param>
        /// <param name="horizontalAlignment">What horizontal alignment does the whole textblock have</param>
        /// <param name="verticalAlignment">What vertical alignment does the whole textblock have</param>
        /// <param name="column">Which column does the textblock belong in</param>
        /// <param name="row">Which row does the textblock belong in</param>
        /// <param name="columnspan">How many columns does the textblock span over</param>
        /// <returns>A textblock object tailored to the arguments</returns>
        public static TextBlock TextBlockConstructor(string text, string name, int fontsize, TextAlignment textAlignment, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment, int column, int row, int columnspan)
        {
            // Declare a new textblock
            TextBlock tb = new TextBlock();

            tb.Text                = text;                // Set text
            tb.Name                = name;
            tb.FontSize            = fontsize;            // Set fontsize
            tb.TextAlignment       = textAlignment;       // Align the text
            tb.HorizontalAlignment = horizontalAlignment; // Align the textblock horizontally
            tb.VerticalAlignment   = verticalAlignment;   // Align the textblock vertically
            Grid.SetColumn(tb, column);                   // Set column
            Grid.SetRow(tb, row);                         // Set row
            Grid.SetColumnSpan(tb, columnspan);           // Set column span
            return(tb);
        }
Beispiel #32
0
        public override void RenderSingleLineText(SvgTextContentElement element, ref Point ctp,
                                                  string text, double rotate, WpfTextPlacement placement)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return;
            }

            double emSize         = GetComputedFontSize(element);
            var    fontFamilyInfo = GetTextFontFamilyInfo(element);

            WpfTextStringFormat stringFormat = GetTextStringFormat(element);

            if (fontFamilyInfo.WpfFontFamilyType == WpfFontFamilyType.Svg)
            {
                WpfTextTuple textInfo = new WpfTextTuple(fontFamilyInfo, emSize, stringFormat, element);
                this.RenderSingleLineText(textInfo, ref ctp, text, rotate, placement);
                return;
            }

            FontFamily  fontFamily  = fontFamilyInfo.Family;
            FontStyle   fontStyle   = fontFamilyInfo.Style;
            FontWeight  fontWeight  = fontFamilyInfo.Weight;
            FontStretch fontStretch = fontFamilyInfo.Stretch;

            // Fix the use of Postscript fonts...
            WpfFontFamilyVisitor fontFamilyVisitor = _context.FontFamilyVisitor;

            if (!string.IsNullOrWhiteSpace(_actualFontName) && fontFamilyVisitor != null)
            {
                WpfFontFamilyInfo familyInfo = fontFamilyVisitor.Visit(_actualFontName,
                                                                       fontFamilyInfo, _context);
                if (familyInfo != null && !familyInfo.IsEmpty)
                {
                    fontFamily  = familyInfo.Family;
                    fontWeight  = familyInfo.Weight;
                    fontStyle   = familyInfo.Style;
                    fontStretch = familyInfo.Stretch;
                }
            }

            WpfSvgPaint fillPaint = new WpfSvgPaint(_context, element, "fill");
            Brush       textBrush = fillPaint.GetBrush();

            WpfSvgPaint strokePaint = new WpfSvgPaint(_context, element, "stroke");
            Pen         textPen     = strokePaint.GetPen();

            if (textBrush == null && textPen == null)
            {
                return;
            }
            if (textBrush == null)
            {
                // If here, then the pen is not null, and so the fill cannot be null.
                // We set this to transparent for stroke only text path...
                textBrush = Brushes.Transparent;
            }
            if (textPen != null)
            {
                textPen.LineJoin = PenLineJoin.Round; // Better for text rendering
            }

            TextDecorationCollection textDecors = GetTextDecoration(element);
            TextAlignment            alignment  = stringFormat.Alignment;

            bool   hasWordSpacing = false;
            string wordSpaceText  = element.GetAttribute("word-spacing");
            double wordSpacing    = 0;

            if (!string.IsNullOrWhiteSpace(wordSpaceText) &&
                double.TryParse(wordSpaceText, out wordSpacing) && !wordSpacing.Equals(0))
            {
                hasWordSpacing = true;
            }

            bool   hasLetterSpacing = false;
            string letterSpaceText  = element.GetAttribute("letter-spacing");
            double letterSpacing    = 0;

            if (!string.IsNullOrWhiteSpace(letterSpaceText) &&
                double.TryParse(letterSpaceText, out letterSpacing) && !letterSpacing.Equals(0))
            {
                hasLetterSpacing = true;
            }

            bool isRotatePosOnly = false;

            IList <WpfTextPosition> textPositions = null;
            int textPosCount = 0;

            if ((placement != null && placement.HasPositions))
            {
                textPositions   = placement.Positions;
                textPosCount    = textPositions.Count;
                isRotatePosOnly = placement.IsRotateOnly;
            }

            var typeFace = new Typeface(fontFamily, fontStyle, fontWeight, fontStretch);

            if (hasLetterSpacing || hasWordSpacing || textPositions != null)
            {
                for (int i = 0; i < text.Length; i++)
                {
                    var           nextText      = new string(text[i], 1);
                    FormattedText formattedText = new FormattedText(nextText,
                                                                    _context.CultureInfo, stringFormat.Direction, typeFace, emSize, textBrush);

                    formattedText.TextAlignment = stringFormat.Alignment;
                    formattedText.Trimming      = stringFormat.Trimming;

                    if (textDecors != null && textDecors.Count != 0)
                    {
                        formattedText.SetTextDecorations(textDecors);
                    }

                    WpfTextPosition?textPosition = null;
                    if (textPositions != null && i < textPosCount)
                    {
                        textPosition = textPositions[i];
                    }

                    //float xCorrection = 0;
                    //if (alignment == TextAlignment.Left)
                    //    xCorrection = emSize * 1f / 6f;
                    //else if (alignment == TextAlignment.Right)
                    //    xCorrection = -emSize * 1f / 6f;

                    double yCorrection = formattedText.Baseline;

                    float rotateAngle = (float)rotate;
                    if (textPosition != null)
                    {
                        if (!isRotatePosOnly)
                        {
                            Point pt = textPosition.Value.Location;
                            ctp.X = pt.X;
                            ctp.Y = pt.Y;
                        }
                        rotateAngle = (float)textPosition.Value.Rotation;
                    }
                    Point textStart = ctp;

                    RotateTransform rotateAt = null;
                    if (!rotateAngle.Equals(0))
                    {
                        rotateAt = new RotateTransform(rotateAngle, textStart.X, textStart.Y);
                        _drawContext.PushTransform(rotateAt);
                    }

                    Point textPoint = new Point(textStart.X, textStart.Y - yCorrection);

                    if (textPen != null || _context.TextAsGeometry)
                    {
                        Geometry textGeometry = formattedText.BuildGeometry(textPoint);
                        if (textGeometry != null && !textGeometry.IsEmpty())
                        {
                            _drawContext.DrawGeometry(textBrush, textPen, ExtractTextPathGeometry(textGeometry));

                            this.IsTextPath = true;
                        }
                        else
                        {
                            _drawContext.DrawText(formattedText, textPoint);
                        }
                    }
                    else
                    {
                        _drawContext.DrawText(formattedText, textPoint);
                    }

                    //float bboxWidth = (float)formattedText.Width;
                    double bboxWidth = formattedText.WidthIncludingTrailingWhitespace;
                    if (alignment == TextAlignment.Center)
                    {
                        bboxWidth /= 2f;
                    }
                    else if (alignment == TextAlignment.Right)
                    {
                        bboxWidth = 0;
                    }

                    //ctp.X += bboxWidth + emSize / 4 + spacing;
                    if (hasLetterSpacing)
                    {
                        ctp.X += bboxWidth + letterSpacing;
                    }
                    if (hasWordSpacing && char.IsWhiteSpace(text[i]))
                    {
                        if (hasLetterSpacing)
                        {
                            ctp.X += wordSpacing;
                        }
                        else
                        {
                            ctp.X += bboxWidth + wordSpacing;
                        }
                    }
                    else
                    {
                        if (!hasLetterSpacing)
                        {
                            ctp.X += bboxWidth;
                        }
                    }

                    if (rotateAt != null)
                    {
                        _drawContext.Pop();
                    }
                }
            }
            else
            {
                FormattedText formattedText = new FormattedText(text, _context.CultureInfo,
                                                                stringFormat.Direction, typeFace, emSize, textBrush);

                formattedText.TextAlignment = stringFormat.Alignment;
                formattedText.Trimming      = stringFormat.Trimming;

                if (textDecors != null && textDecors.Count != 0)
                {
                    formattedText.SetTextDecorations(textDecors);
                }

                //float xCorrection = 0;
                //if (alignment == TextAlignment.Left)
                //    xCorrection = emSize * 1f / 6f;
                //else if (alignment == TextAlignment.Right)
                //    xCorrection = -emSize * 1f / 6f;

                double yCorrection = formattedText.Baseline;

                float rotateAngle = (float)rotate;
                Point textPoint   = new Point(ctp.X, ctp.Y - yCorrection);

                RotateTransform rotateAt = null;
                if (!rotateAngle.Equals(0))
                {
                    rotateAt = new RotateTransform(rotateAngle, ctp.X, ctp.Y);
                    _drawContext.PushTransform(rotateAt);
                }

                if (textPen != null || _context.TextAsGeometry)
                {
                    Geometry textGeometry = formattedText.BuildGeometry(textPoint);
                    if (textGeometry != null && !textGeometry.IsEmpty())
                    {
                        _drawContext.DrawGeometry(textBrush, textPen,
                                                  ExtractTextPathGeometry(textGeometry));

                        this.IsTextPath = true;
                    }
                    else
                    {
                        _drawContext.DrawText(formattedText, textPoint);
                    }
                }
                else
                {
                    _drawContext.DrawText(formattedText, textPoint);
                }

                //float bboxWidth = (float)formattedText.Width;
                double bboxWidth = formattedText.WidthIncludingTrailingWhitespace;
                if (alignment == TextAlignment.Center)
                {
                    bboxWidth /= 2f;
                }
                else if (alignment == TextAlignment.Right)
                {
                    bboxWidth = 0;
                }

                //ctp.X += bboxWidth + emSize / 4;
                ctp.X += bboxWidth;

                if (rotateAt != null)
                {
                    _drawContext.Pop();
                }
            }
        }
Beispiel #33
0
        private void RenderTextRun(WpfTextTuple textInfo, ref Point ctp,
                                   string text, double rotate, WpfTextPlacement placement)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return;
            }

            WpfFontFamilyInfo     familyInfo   = textInfo.Item1;
            double                emSize       = textInfo.Item2;
            WpfTextStringFormat   stringFormat = textInfo.Item3;
            SvgTextContentElement element      = textInfo.Item4;

            FontFamily  fontFamily  = familyInfo.Family;
            FontWeight  fontWeight  = familyInfo.Weight;
            FontStyle   fontStyle   = familyInfo.Style;
            FontStretch fontStretch = familyInfo.Stretch;

            WpfSvgPaint fillPaint = new WpfSvgPaint(_context, element, "fill");
            Brush       textBrush = fillPaint.GetBrush();

            WpfSvgPaint strokePaint = new WpfSvgPaint(_context, element, "stroke");
            Pen         textPen     = strokePaint.GetPen();

            if (textBrush == null && textPen == null)
            {
                return;
            }
            if (textBrush == null)
            {
                // If here, then the pen is not null, and so the fill cannot be null.
                // We set this to transparent for stroke only text path...
                textBrush = Brushes.Transparent;
            }
            if (textPen != null)
            {
                textPen.LineJoin   = PenLineJoin.Miter; // Better for text rendering
                textPen.MiterLimit = 1;
            }

            TextDecorationCollection textDecors = GetTextDecoration(element);

            if (textDecors == null)
            {
                SvgTextElement textElement = element.ParentNode as SvgTextElement;

                if (textElement != null)
                {
                    textDecors = GetTextDecoration(textElement);
                }
            }

            TextAlignment alignment = stringFormat.Alignment;

            bool   hasWordSpacing = false;
            string wordSpaceText  = element.GetAttribute("word-spacing");
            double wordSpacing    = 0;

            if (!string.IsNullOrWhiteSpace(wordSpaceText) &&
                double.TryParse(wordSpaceText, out wordSpacing) && !wordSpacing.Equals(0))
            {
                hasWordSpacing = true;
            }

            bool   hasLetterSpacing = false;
            string letterSpaceText  = element.GetAttribute("letter-spacing");
            double letterSpacing    = 0;

            if (!string.IsNullOrWhiteSpace(letterSpaceText) &&
                double.TryParse(letterSpaceText, out letterSpacing) && !letterSpacing.Equals(0))
            {
                hasLetterSpacing = true;
            }

            bool isRotatePosOnly = false;

            IList <WpfTextPosition> textPositions = null;
            int textPosCount = 0;

            if ((placement != null && placement.HasPositions))
            {
                textPositions   = placement.Positions;
                textPosCount    = textPositions.Count;
                isRotatePosOnly = placement.IsRotateOnly;
            }

            WpfTextBuilder textBuilder = WpfTextBuilder.Create(familyInfo, this.TextCulture, emSize);

            this.IsTextPath = true;

            if (textPositions != null && textPositions.Count != 0)
            {
                if (textPositions.Count == text.Trim().Length) //TODO: Best way to handle this...
                {
                    text = text.Trim();
                }
            }

            if (hasLetterSpacing || hasWordSpacing || textPositions != null)
            {
                double spacing = Convert.ToDouble(letterSpacing);

                int startSpaces = 0;
                for (int i = 0; i < text.Length; i++)
                {
                    if (char.IsWhiteSpace(text[i]))
                    {
                        startSpaces++;
                    }
                    else
                    {
                        break;
                    }
                }

                int j = 0;

                string inputText = string.Empty;
                for (int i = 0; i < text.Length; i++)
                {
                    // Avoid rendering only spaces at the start of text run...
                    if (i == 0 && startSpaces != 0)
                    {
                        inputText = text.Substring(0, startSpaces + 1);
                        i        += startSpaces;
                    }
                    else
                    {
                        inputText = new string(text[i], 1);
                    }

                    if (this.IsMeasuring)
                    {
                        var textSize = textBuilder.MeasureText(element, inputText);
                        this.AddTextWidth(ctp, textSize.Width);
                        continue;
                    }

                    textBuilder.Trimming      = stringFormat.Trimming;
                    textBuilder.TextAlignment = stringFormat.Alignment;

                    if (textDecors != null && textDecors.Count != 0)
                    {
                        textBuilder.SetTextDecorations(textDecors);
                    }

                    WpfTextPosition?textPosition = null;
                    if (textPositions != null && j < textPosCount)
                    {
                        textPosition = textPositions[j];
                    }

                    //float xCorrection = 0;
                    //if (alignment == TextAlignment.Left)
                    //    xCorrection = emSize * 1f / 6f;
                    //else if (alignment == TextAlignment.Right)
                    //    xCorrection = -emSize * 1f / 6f;

                    double yCorrection = textBuilder.Baseline;

                    float rotateAngle = (float)rotate;
                    if (textPosition != null)
                    {
                        if (!isRotatePosOnly)
                        {
                            Point pt = textPosition.Value.Location;
                            ctp.X = pt.X;
                            ctp.Y = pt.Y;
                        }
                        rotateAngle = (float)textPosition.Value.Rotation;
                    }
                    Point textStart = ctp;

                    RotateTransform rotateAt = null;
                    if (!rotateAngle.Equals(0))
                    {
                        rotateAt = new RotateTransform(rotateAngle, textStart.X, textStart.Y);
                        _drawContext.PushTransform(rotateAt);
                    }

                    Point textPoint = new Point(ctp.X, ctp.Y - yCorrection);

                    Geometry textGeometry = textBuilder.Build(element, inputText, textPoint.X, textPoint.Y);
                    if (textGeometry != null && !textGeometry.IsEmpty())
                    {
                        _drawContext.DrawGeometry(textBrush, textPen,
                                                  ExtractTextPathGeometry(textGeometry));

                        this.IsTextPath = true;
                    }

                    //float bboxWidth = (float)formattedText.Width;
                    double bboxWidth = textGeometry.Bounds.Width;
                    if (alignment == TextAlignment.Center)
                    {
                        bboxWidth /= 2f;
                    }
                    else if (alignment == TextAlignment.Right)
                    {
                        bboxWidth = 0;
                    }

                    //ctp.X += bboxWidth + emSize / 4 + spacing;
                    if (hasLetterSpacing)
                    {
                        ctp.X += bboxWidth + letterSpacing;
                    }
                    if (hasWordSpacing && char.IsWhiteSpace(text[i]))
                    {
                        if (hasLetterSpacing)
                        {
                            ctp.X += wordSpacing;
                        }
                        else
                        {
                            ctp.X += bboxWidth + wordSpacing;
                        }
                    }
                    else
                    {
                        if (!hasLetterSpacing)
                        {
                            ctp.X += bboxWidth;
                        }
                    }

                    if (rotateAt != null)
                    {
                        _drawContext.Pop();
                    }
                    j++;
                }
            }
            else
            {
                if (this.IsMeasuring)
                {
                    var textSize = textBuilder.MeasureText(element, text);
                    this.AddTextWidth(ctp, textSize.Width);
                    return;
                }

                var textContext = this.TextContext;
                if (textContext != null && textContext.IsPositionChanged(element) == false)
                {
                    if (alignment == TextAlignment.Center && this.TextWidth > 0)
                    {
                        alignment = TextAlignment.Left;
                    }
                }

                textBuilder.TextAlignment = alignment;
                textBuilder.Trimming      = stringFormat.Trimming;

                if (textDecors != null && textDecors.Count != 0)
                {
                    textBuilder.SetTextDecorations(textDecors);
                }

                //float xCorrection = 0;
                //if (alignment == TextAlignment.Left)
                //    xCorrection = emSize * 1f / 6f;
                //else if (alignment == TextAlignment.Right)
                //    xCorrection = -emSize * 1f / 6f;

                double yCorrection = textBuilder.Baseline;

                float rotateAngle = (float)rotate;
                Point textPoint   = new Point(ctp.X, ctp.Y - yCorrection);

                RotateTransform rotateAt = null;
                if (!rotateAngle.Equals(0))
                {
                    rotateAt = new RotateTransform(rotateAngle, ctp.X, ctp.Y);
                    _drawContext.PushTransform(rotateAt);
                }

                Geometry textGeometry = textBuilder.Build(element, text, textPoint.X, textPoint.Y);
                if (textGeometry != null && !textGeometry.IsEmpty())
                {
                    _drawContext.DrawGeometry(textBrush, textPen,
                                              ExtractTextPathGeometry(textGeometry));
                }

                //float bboxWidth = (float)formattedText.Width;
//                double bboxWidth = textGeometry.Bounds.Width;
                double bboxWidth = textBuilder.Width;

                if (alignment == TextAlignment.Center)
                {
                    bboxWidth /= 2f;
                }
                else if (alignment == TextAlignment.Right)
                {
                    bboxWidth = 0;
                }

                //ctp.X += bboxWidth + emSize / 4;
                ctp.X += bboxWidth;

                if (rotateAt != null)
                {
                    _drawContext.Pop();
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="DrawableTextAlignment"/> class.
 /// </summary>
 /// <param name="alignment">Text alignment.</param>
 public DrawableTextAlignment(TextAlignment alignment)
 {
     Alignment = alignment;
 }
Beispiel #35
0
 public SignalNameEditor(string initialText, double maxWidth, TextAlignment textAlignment)
 {
     Text          = initialText;
     MaxWidth      = maxWidth;
     TextAlignment = textAlignment;
 }
Beispiel #36
0
 public ColumnInfo(string labelName, float?fixedWidth = null)
 {
     LabelName  = labelName;
     FixedWidth = fixedWidth;
     Alignment  = TextAlignment.Center;
 }
        public BaseInputC(int FieldWidth = 80, VerticalAlignment VertAlign = VerticalAlignment.Center, HorizontalAlignment HorAlign = HorizontalAlignment.Center, _fontsz FontSize = _fontsz.Standard, TextAlignment TA = TextAlignment.Left,
                          string S       = "", TextWrapping TW = TextWrapping.Wrap)

        {
            HorizontalAlignment = HorAlign;
            VerticalAlignment   = VertAlign;
            Width = FieldWidth;
            BlurEffect ErrorFlare = new BlurEffect {
                KernelType = KernelType.Gaussian, Radius = 10, RenderingBias = RenderingBias.Performance
            };

            myrct = new Rectangle {
                Name   = "ErrorRectangle", Fill = Brushes.Red, Opacity = 0.33, StrokeThickness = 1,
                Effect = ErrorFlare, Visibility = Visibility.Hidden
            };
            BaseTextBox = new TextBox {
                Name = "TextBox", BorderBrush = Brushes.LightGray, Text = S, TextAlignment = TA, TextWrapping = TW,
                HorizontalAlignment = HorAlign, VerticalAlignment = VertAlign
            };
            switch (FontSize)
            {
            case _fontsz.Small:
                Height               = 24;
                BaseTextBox.Height   = 16;
                BaseTextBox.Width    = FieldWidth - 8;
                BaseTextBox.Margin   = new Thickness(4, 4, 0, 0);
                BaseTextBox.FontSize = 8;
                break;

            case _fontsz.Smaller:
                Height               = 26;
                BaseTextBox.Height   = 18;
                BaseTextBox.Width    = FieldWidth - 8;
                BaseTextBox.Margin   = new Thickness(4, 4, 0, 0);
                BaseTextBox.FontSize = 10;
                break;

            case _fontsz.Standard:
                Height               = 28;
                BaseTextBox.Height   = 20;
                BaseTextBox.Width    = FieldWidth - 8;
                BaseTextBox.Margin   = new Thickness(4, 4, 0, 0);
                BaseTextBox.FontSize = 12;
                break;

            case _fontsz.Medium:
                Height               = 34;
                BaseTextBox.Height   = 26;
                BaseTextBox.Width    = FieldWidth - 8;
                BaseTextBox.Margin   = new Thickness(4, 4, 0, 0);
                BaseTextBox.FontSize = 16;
                break;

            case _fontsz.Large:
                Height               = 36;
                BaseTextBox.Height   = 28;
                BaseTextBox.Width    = FieldWidth - 8;
                BaseTextBox.Margin   = new Thickness(4, 4, 0, 0);
                BaseTextBox.FontSize = 18;
                break;

            case _fontsz.VeryLarge:
                Height               = 44;
                BaseTextBox.Height   = 36;
                BaseTextBox.Width    = FieldWidth - 8;
                BaseTextBox.Margin   = new Thickness(4, 4, 0, 0);
                BaseTextBox.FontSize = 24;
                break;

            default:
                break;
            }
            Children.Add(myrct);
            Children.Add(BaseTextBox);
        }
Beispiel #38
0
        internal void InternalDraw(CommandList commandList, ref StringProxy text, ref InternalDrawCommand drawCommand, TextAlignment alignment)
        {
            // If the text is mirrored, offset the start position accordingly.
            if (drawCommand.SpriteEffects != SpriteEffects.None)
            {
                drawCommand.Origin -= MeasureString(ref text, ref drawCommand.FontSize) * AxisIsMirroredTable[(int)drawCommand.SpriteEffects & 3];
            }

            // Draw each character in turn.
            ForEachGlyph(commandList, ref text, ref drawCommand.FontSize, internalDrawGlyphAction, ref drawCommand, alignment, true);
        }
Beispiel #39
0
 public ReplacementItem(int ColumnWidth, string Number, string Content, string TextColor, int FontSize, FontAttributes FontAttributes, TextAlignment HorizontalTextAlignment)
 {
     this.ColumnWidth             = ColumnWidth;
     this.Number                  = Number;
     this.Content                 = Content;
     this.TextColor               = TextColor;
     this.FontSize                = FontSize;
     this.FontAttributes          = FontAttributes;
     this.HorizontalTextAlignment = HorizontalTextAlignment;
 }
 public static UITextAlignment ToPlatform(this TextAlignment alignment, IView view)
 => alignment.ToPlatform(view.FlowDirection == FlowDirection.LeftToRight);
 /// <summary>
 /// For binding use only.
 /// </summary>
 public static void SetAppBarTitleTextAlignment(BindableObject view, TextAlignment textAlignment)
 {
     view.SetValue(AppBarTitleTextAlignmentProperty, textAlignment);
 }
Beispiel #42
0
        // Text alignment and transformation

        public static TThis SetAlignment <THelper, TThis, TWrapper>(this Component <THelper, TThis, TWrapper> component, TextAlignment alignment)
            where THelper : BootstrapHelper <THelper>
            where TThis : Tag <THelper, TThis, TWrapper>
            where TWrapper : TagWrapper <THelper>, new()
        {
            return(component.GetThis().ToggleCss(alignment));
        }
 public void DrawString(string s, float x, float y, float width, float height, LineBreakMode lineBreak, TextAlignment align)
 {
 }
Beispiel #44
0
 private Label CreateLabel(string text, TextAlignment horz = TextAlignment.Start)
 {
     return(MainPage.CreateLabel(text, horz));
 }
Beispiel #45
0
        private void ForEachGlyph <T>(CommandList commandList, ref StringProxy text, ref Vector2 fontSize, GlyphAction <T> action, ref T parameters, TextAlignment scanOrder, bool updateGpuResources, Vector2?elementsize = null)
        {
            if (scanOrder == TextAlignment.Left)
            {
                // scan the whole text only one time following the text letter order
                ForGlyph(commandList, ref text, ref fontSize, action, ref parameters, 0, text.Length, updateGpuResources);
            }
            else // scan the text line by line incrementing y start position
            {
                // measure the whole string in order to be able to determine xStart
                var wholeSize = elementsize ?? MeasureString(ref text, ref fontSize);

                // scan the text line by line
                var yStart     = 0f;
                var startIndex = 0;
                var endIndex   = FindCariageReturn(ref text, 0);
                while (startIndex < text.Length)
                {
                    // measure the size of the current line
                    var lineSize = Vector2.Zero;
                    ForGlyph(commandList, ref text, ref fontSize, MeasureStringGlyph, ref lineSize, startIndex, endIndex, updateGpuResources);

                    // Determine the start position of the line along the x axis
                    // We round this value to the closest integer to force alignment of all characters to the same pixels
                    // Otherwise the starting offset can fall just in between two pixels and due to float imprecision
                    // some characters can be aligned to the pixel before and others to the pixel after, resulting in gaps and character overlapping
                    var xStart = (scanOrder == TextAlignment.Center) ? (wholeSize.X - lineSize.X) / 2 : wholeSize.X - lineSize.X;
                    xStart = (float)Math.Round(xStart);

                    // scan the line
                    ForGlyph(commandList, ref text, ref fontSize, action, ref parameters, startIndex, endIndex, updateGpuResources, xStart, yStart);

                    // update variable before going to next line
                    yStart    += GetTotalLineSpacing(fontSize.Y);
                    startIndex = endIndex + 1;
                    endIndex   = FindCariageReturn(ref text, startIndex);
                }
            }
        }
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null)
            {
                return(false);
            }

            if (parameter.ToString() == "bold")
            {
                FontWeight weight = (FontWeight)value;
                if (weight == FontWeights.Bold)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            else if (parameter.ToString() == "italic")
            {
                FontStyle weight = (FontStyle)value;
                if (weight == FontStyles.Italic)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            else if (parameter.ToString() == "left")
            {
                TextAlignment weight = (TextAlignment)value;
                if (weight == TextAlignment.Left)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            else if (parameter.ToString() == "center")
            {
                TextAlignment weight = (TextAlignment)value;
                if (weight == TextAlignment.Center)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                TextAlignment weight = (TextAlignment)value;
                if (weight == TextAlignment.Right)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
        }
Beispiel #47
0
        /// <summary>
        /// Draws a multi-string.
        /// WARNING! This grows more CPU-intensive as the number of words grow (only if word wrap enabled). It is recommended to use the DrawMultiLineText method instead - it uses caching.
        /// </summary>
        /// <param name="fnt">A reference to a SpriteFont object.</param>
        /// <param name="text">The text to be drawn. <remarks>If the text contains \n it
        /// will be treated as a new line marker and the text will drawn acordingy.</remarks></param>
        /// <param name="r">The screen rectangle that the rext should be drawn inside of.</param>
        /// <param name="col">The color of the text that will be drawn.</param>
        /// <param name="align">Specified the alignment within the specified screen rectangle.</param>
        /// <param name="textBounds">Returns a rectangle representing the size of the bouds of
        /// the text that was drawn.</param>
        /// <param name="cachedLines">This parameter is internal. Do not use it, merely throw away the variable.</param>
        private static void SetupNewMultilineString(BitmapFontGroup fnt, string text, Rectangle r,
                                                    Color col, TextAlignment align, out Rectangle textBounds, out List <MultilineFragment> cachedLines, bool degrading)
        {
            textBounds = r;
            if (text == string.Empty)
            {
                cachedLines = new List <MultilineFragment>();
                return;
            }

            Data d = new Data();

            d.FontGroup          = fnt;
            d.ReadyFragment      = new StringBuilder();
            d.Builder            = new StringBuilder();
            d.CurrentFont        = d.FontGroup.Regular;
            d.CurrentX           = 0;
            d.CurrentY           = 0;
            d.TotalNumberOfLines = 0;
            d.Width      = r.Width;
            d.Height     = r.Height;
            d.IsBold     = false;
            d.IsItalics  = false;
            d.LineHeight = d.FontGroup.Regular.LineHeight;
            d.Color      = col;
            d.End        = false;
            d.Lines      = new List <List <MultilineFragment> >();
            d.ThisLine   = new List <MultilineFragment>();
            if (d.Height >= d.LineHeight)
            {
                foreach (char t in text)
                {
                    if (t == '{')
                    {
                        // Flush and write.
                        FlushAndWrite(d);
                        // Ready to change mode.
                    }
                    else if (t == '}')
                    {
                        // Change mode.
                        switch (d.Builder.ToString())
                        {
                        case "b":
                            d.IsBold = !d.IsBold;
                            d.UpdateFont();
                            break;

                        case "i":
                            d.IsItalics = !d.IsItalics;
                            d.UpdateFont();
                            break;

                        case "/b":
                            d.IsBold = !d.IsBold;
                            d.UpdateFont();
                            break;

                        case "/i":
                            d.IsItalics = !d.IsItalics;
                            d.UpdateFont();
                            break;

                        default:
                            string tag = d.Builder.ToString();
                            if (tag.StartsWith("icon:"))
                            {
                                Texture2D icon = Library.Icons[tag.Substring(5)];
                                d.Builder.Clear();
                                // Now add icon.
                                int iconwidth      = d.LineHeight;
                                int remainingSpace = (int)(d.Width - d.CurrentX);
                                if (remainingSpace > iconwidth + 3)
                                {
                                    d.ThisLine.Add(new MultilineFragment(icon,
                                                                         new Vector2(d.CurrentX, d.CurrentY), iconwidth));
                                    d.CurrentX += iconwidth + 3;
                                }
                                else
                                {
                                    FlushAndWrite(d);
                                    GoToNextLine(d);

                                    d.ThisLine.Add(new MultilineFragment(icon,
                                                                         new Vector2(d.CurrentX, d.CurrentY), iconwidth));
                                    d.CurrentX += iconwidth + 3;
                                }

                                break;
                            }
                            else if (tag[0] == '/')
                            {
                                d.Color = col;
                            }
                            else
                            {
                                d.Color = ColorFromString(tag);
                            }

                            break;
                        }

                        d.Builder.Clear();
                    }
                    else if (t == ' ')
                    {
                        // Flush.
                        // Add builder to ready.
                        string without = d.ReadyFragment.ToString();
                        d.ReadyFragment.Append(d.Builder);
                        if (d.CurrentFont.MeasureString(d.ReadyFragment.ToString()).Width <= d.Width - d.CurrentX)
                        {
                            // It will fit.
                            d.ReadyFragment.Append(' ');
                            d.Builder.Clear();
                        }
                        else
                        {
                            // It would not fit.
                            d.ReadyFragment = new StringBuilder(without);
                            string newone = d.Builder.ToString();
                            d.Builder = new StringBuilder();
                            FlushAndWrite(d, true);
                            if (!d.End)
                            {
                                d.Builder.Append(newone);
                                FlushAndWrite(d);
                                d.Builder.Clear();
                                d.Builder.Append(' ');
                            }
                        }

                        // Write if overflowing.
                    }
                    else if (t == '\n')
                    {
                        // Flush and write.
                        FlushAndWrite(d);
                        // Skip to new line automatically.
                        GoToNextLine(d);
                    }
                    else
                    {
                        d.Builder.Append(t);
                    }

                    if (d.End)
                    {
                        break;
                    }
                }

                // Flush and write.
                FlushAndWrite(d);
                if (d.ThisLine.Count > 0)
                {
                    FinishLine(d);
                    d.TotalNumberOfLines += 1;
                }
            }

            if (d.End && degrading && fnt.DegradesTo != null)
            {
                SetupNewMultilineString(fnt.DegradesTo, text, r, col, align, out textBounds, out cachedLines, degrading);
                return;
            }

            // Output.
            textBounds = new Rectangle(r.X, r.Y, (int)d.Maximumwidthencountered, d.TotalNumberOfLines * d.LineHeight);
            int yoffset = 0;

            switch (align)
            {
            case TextAlignment.TopLeft:
            case TextAlignment.Top:
            case TextAlignment.TopRight:
                break;

            case TextAlignment.Bottom:
            case TextAlignment.BottomLeft:
            case TextAlignment.BottomRight:
                yoffset = r.Height - d.TotalNumberOfLines * d.LineHeight;
                break;

            case TextAlignment.Middle:
            case TextAlignment.Left:
            case TextAlignment.Right:
                yoffset = (r.Height - (d.TotalNumberOfLines * d.LineHeight)) / 2;
                break;
            }
            cachedLines = new List <MultilineFragment>();
            foreach (var line in d.Lines)
            {
                foreach (var fragment in line)
                {
                    if (fragment.Text == "")
                    {
                        continue;
                    }
                    float xoffset   = 0;
                    float lineWidth = line.Sum(frg => frg.Width);
                    switch (align)
                    {
                    case TextAlignment.Right:
                    case TextAlignment.TopRight:
                    case TextAlignment.BottomRight:
                        xoffset = r.Width - lineWidth;
                        break;

                    case TextAlignment.Middle:
                    case TextAlignment.Top:
                    case TextAlignment.Bottom:
                        xoffset = (r.Width - lineWidth) / 2;
                        break;
                    }
                    fragment.PositionOffset += new Vector2(xoffset, yoffset);
                    fragment.PositionOffset  = new Vector2((int)fragment.PositionOffset.X, (int)fragment.PositionOffset.Y);
                    cachedLines.Add(fragment);
                }
            }
        }
Beispiel #48
0
        public static void Main(string[] args)
        {
            var        fonts      = new FontCollection();
            FontFamily font       = fonts.Install(@"Fonts\SixLaborsSampleAB.ttf");
            FontFamily fontWoff   = fonts.Install(@"Fonts\SixLaborsSampleAB.woff");
            FontFamily carter     = fonts.Install(@"Fonts\CarterOne.ttf");
            FontFamily wendy_One  = fonts.Install(@"Fonts\WendyOne-Regular.ttf");
            FontFamily colorEmoji = fonts.Install(@"Fonts\Twemoji Mozilla.ttf");
            FontFamily font2      = fonts.Install(@"Fonts\OpenSans-Regular.ttf");
            FontFamily emojiFont  = SystemFonts.Find("Segoe UI Emoji");

            // fallback font tests
            RenderTextProcessor(colorEmoji, "a😀d", pointSize: 72, fallbackFonts: new[] { font2 });
            RenderText(colorEmoji, "a😀d", pointSize: 72, fallbackFonts: new[] { font2 });

            RenderText(colorEmoji, "😀", pointSize: 72, fallbackFonts: new[] { font2 });
            RenderText(emojiFont, "😀", pointSize: 72, fallbackFonts: new[] { font2 });
            RenderText(font2, string.Empty, pointSize: 72, fallbackFonts: new[] { emojiFont });
            RenderText(font2, "😀 Hello World! 😀", pointSize: 72, fallbackFonts: new[] { emojiFont });

            //// general

            RenderText(font, "abc", 72);
            RenderText(font, "ABd", 72);
            RenderText(fontWoff, "abe", 72);
            RenderText(fontWoff, "ABf", 72);
            RenderText(font2, "ov", 72);
            RenderText(font2, "a\ta", 72);
            RenderText(font2, "aa\ta", 72);
            RenderText(font2, "aaa\ta", 72);
            RenderText(font2, "aaaa\ta", 72);
            RenderText(font2, "aaaaa\ta", 72);
            RenderText(font2, "aaaaaa\ta", 72);
            RenderText(font2, "Hello\nWorld", 72);
            RenderText(carter, "Hello\0World", 72);
            RenderText(wendy_One, "Hello\0World", 72);

            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 4
            }, "\t\tx");
            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 4
            }, "\t\t\tx");
            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 4
            }, "\t\t\t\tx");
            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 4
            }, "\t\t\t\t\tx");

            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 0
            }, "Zero\tTab");

            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 0
            }, "Zero\tTab");
            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 1
            }, "One\tTab");
            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 6
            }, "\tTab Then Words");
            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 1
            }, "Tab Then Words");
            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 1
            }, "Words Then Tab\t");
            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 1
            }, "                 Spaces Then Words");
            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 1
            }, "Words Then Spaces                 ");
            RenderText(new RendererOptions(new Font(font2, 72))
            {
                TabWidth = 1
            }, "\naaaabbbbccccddddeeee\n\t\t\t3 tabs\n\t\t\t\t\t5 tabs");

            RenderText(new Font(SystemFonts.Find("Arial"), 20f, FontStyle.Regular), "á é í ó ú ç ã õ", 200, 50);
            RenderText(new Font(SystemFonts.Find("Arial"), 10f, FontStyle.Regular), "PGEP0JK867", 200, 50);

            RenderText(new RendererOptions(SystemFonts.CreateFont("consolas", 72))
            {
                TabWidth = 4
            }, "xxxxxxxxxxxxxxxx\n\txxxx\txxxx\n\t\txxxxxxxx\n\t\t\txxxx");

            BoundingBoxes.Generate("a b c y q G H T", SystemFonts.CreateFont("arial", 40f));

            TextAlignment.Generate(SystemFonts.CreateFont("arial", 50f));
            TextAlignmentWrapped.Generate(SystemFonts.CreateFont("arial", 50f));

            var sb = new StringBuilder();

            for (char c = 'a'; c <= 'z'; c++)
            {
                sb.Append(c);
            }

            for (char c = 'A'; c <= 'Z'; c++)
            {
                sb.Append(c);
            }

            for (char c = '0'; c <= '9'; c++)
            {
                sb.Append(c);
            }

            string text = sb.ToString();

            foreach (FontFamily f in fonts.Families)
            {
                RenderText(f, text, 72);
            }

            FontFamily simsum = SystemFonts.Find("SimSun");

            RenderText(simsum, "这是一段长度超出设定的�行宽度的文本,但是没有在设定的宽度处�行。这段文本用于演示问题。希望�以修�。如果有需��以�系我。", 16);
        }
Beispiel #49
0
 /// <summary>
 /// Generates WPF XAML for the markdown element.
 /// </summary>
 /// <param name="Output">XAML will be output here.</param>
 /// <param name="TextAlignment">Alignment of text in element.</param>
 public override void GenerateXAML(XmlWriter Output, TextAlignment TextAlignment)
 {
     Output.WriteElementString("Separator", string.Empty);
 }
Beispiel #50
0
    public static TextMesh CreateWorldText(Transform parent, string text, Vector3 localPosition, int fontSize, Color color, TextAnchor textAnchor, TextAlignment textAlignment, int sortingOrder)
    {
        GameObject gameObject = new GameObject("World_Text", typeof(TextMesh));
        Transform  transform  = gameObject.transform;

        transform.SetParent(parent, false);
        transform.localPosition = localPosition;
        TextMesh textMesh = gameObject.GetComponent <TextMesh>();

        textMesh.anchor    = textAnchor;
        textMesh.alignment = textAlignment;
        textMesh.text      = text;
        textMesh.fontSize  = fontSize;
        textMesh.color     = color;
        textMesh.GetComponent <MeshRenderer>().sortingOrder = sortingOrder;
        return(textMesh);
    }
Beispiel #51
0
        public void DrawString(string s, float x, float y, float width, float height, LineBreakMode lineBreak, TextAlignment align)
        {
            if (_lastFont == null)
            {
                return;
            }
            var fm = GetFontMetrics();
            var xx = x;
            var yy = y;

            if (align == TextAlignment.Center)
            {
                xx = (x + width / 2) - (fm.StringWidth(s) / 2);
            }
            else if (align == TextAlignment.Right)
            {
                xx = (x + width) - fm.StringWidth(s);
            }

            DrawString(s, xx, yy);
        }
Beispiel #52
0
 public static TextMesh CreateWorldText(string text, Transform parent = null, Vector3 localPosition = default(Vector3), int fontSize = 40, Color?color = null, TextAnchor textAnchor = TextAnchor.UpperLeft, TextAlignment textAlignment = TextAlignment.Left, int sortingOrder = sortingOrderDefault)
 {
     if (color == null)
     {
         color = Color.white;
     }
     return(CreateWorldText(parent, text, localPosition, fontSize, (Color)color, textAnchor, textAlignment, sortingOrder));
 }
Beispiel #53
0
 protected override void setTextAlignment(TextAlignment alignment)
 {
     Label.TextAlignment = ( UITextAlignment )alignment;
 }
Beispiel #54
0
 public TextButton(Screen screen, SpriteFont font, UIAlignment alignment, int xOffset, int yOffset, int hitBoxPadding, TextAlignment textAlignment, string text, int outline, Color selectedColor, Color deselectedColor, Action onActivate, Action onMouseOver, Action onMouseOut)
 {
     _screen          = screen;
     _spriteBatch     = _screen.screenSystem.spriteBatch;
     _font            = font;
     _alignment       = alignment;
     _xOffset         = xOffset;
     _yOffset         = yOffset;
     _hitBoxPadding   = hitBoxPadding;
     _textAlignment   = textAlignment;
     this.text        = text;
     _outline         = outline;
     _selectedColor   = selectedColor;
     _deselectedColor = deselectedColor;
     _onActivate      = onActivate;
     _onMouseOver     = onMouseOver;
     _onMouseOut      = onMouseOut;
     _color           = deselectedColor;
 }
Beispiel #55
0
 public static void SetTextAlignment(this HtmlStyleDictionary style, TextAlignment textAlignment, IHtmlValueConverter converter)
 {
     style.SetValue("text-align", converter.ToTextAlignmentString(textAlignment));
 }
Beispiel #56
0
 public TextButton(Screen screen, SpriteFont font, UIAlignment alignment, int xOffset, int yOffset, int hitBoxPadding, TextAlignment textAlignment, string text, int outline, Color selectedColor, Color deselectedColor, Action onActivate)
     : this(screen, font, alignment, xOffset, yOffset, hitBoxPadding, textAlignment, text, outline, selectedColor, deselectedColor, onActivate, null, null)
 {
     _onMouseOver = () => { select(); };
     _onMouseOut  = () => { deselect(); };
 }
Beispiel #57
0
        /// <summary>
        /// Generates XAML for the markdown element.
        /// </summary>
        /// <param name="Output">XAML will be output here.</param>
        /// <param name="Settings">XAML settings.</param>
        /// <param name="TextAlignment">Alignment of text in element.</param>
        /// <param name="Items">Multimedia items.</param>
        /// <param name="ChildNodes">Child nodes.</param>
        /// <param name="AloneInParagraph">If the element is alone in a paragraph.</param>
        /// <param name="Document">Markdown document containing element.</param>
        public override void GenerateXAML(XmlWriter Output, XamlSettings Settings, TextAlignment TextAlignment, MultimediaItem[] Items,
                                          IEnumerable <MarkdownElement> ChildNodes, bool AloneInParagraph, MarkdownDocument Document)
        {
            string Source;
            int    i;
            int?   Width;
            int?   Height;

            foreach (MultimediaItem Item in Items)
            {
                Width  = Item.Width;
                Height = Item.Height;

                if ((Source = Item.Url).StartsWith("data:", StringComparison.CurrentCultureIgnoreCase) && (i = Item.Url.IndexOf("base64,")) > 0)
                {
                    byte[] Data = Convert.FromBase64String(Item.Url.Substring(i + 7));
                    using (SKBitmap Bitmap = SKBitmap.Decode(Data))
                    {
                        Width  = Bitmap.Width;
                        Height = Bitmap.Height;
                    }

                    string FileName = Path.GetTempFileName();
                    System.IO.File.WriteAllBytes(FileName, Data);

                    Source = FileName;

                    lock (synchObject)
                    {
                        if (temporaryFiles == null)
                        {
                            temporaryFiles   = new Dictionary <string, bool>();
                            Log.Terminating += CurrentDomain_ProcessExit;
                        }

                        temporaryFiles[FileName] = true;
                    }
                }

                Output.WriteStartElement("Image");
                Output.WriteAttributeString("Source", Document.CheckURL(Source, null));

                if (Width.HasValue)
                {
                    Output.WriteAttributeString("Width", Width.Value.ToString());
                }

                if (Height.HasValue)
                {
                    Output.WriteAttributeString("Height", Height.Value.ToString());
                }

                if (!string.IsNullOrEmpty(Item.Title))
                {
                    Output.WriteAttributeString("ToolTip", Item.Title);
                }

                Output.WriteEndElement();

                break;
            }
        }
        void ITextAlignmentElement.OnHorizontalTextAlignmentPropertyChanged(TextAlignment oldValue, TextAlignment newValue)
        {
#pragma warning disable 0618 // retain until XAlign removed
            OnPropertyChanged(nameof(XAlign));
#pragma warning restore
        }
Beispiel #59
0
        public GridEXColumn AddColumn(string colName, ColumnType colType, int width, ColumnBoundMode boundMode, string caption, FilterEditType editType, TextAlignment align)
        {
            if (this.RootTable == null)
            {
                this.RootTable = new GridEXTable();
            }
            GridEXColumn col = this.RootTable.Columns.Add(colName, colType);

            col.Width          = width;
            col.BoundMode      = boundMode;
            col.DataMember     = colName;
            col.Caption        = caption;
            col.FilterEditType = editType;
            col.TextAlignment  = align;
            return(col);
        }
Beispiel #60
0
        public override void OnInspectorGUI()
        {
            // Draw TextFx inspector section
            TextFxBaseInspector.DrawTextFxInspectorSection(this, animationManager, () => {
                RefreshTextCurveData();
            });

//			DrawDefaultInspector();

            textfx_instance = (TextFxNative)target;

            m_old_text              = textfx_instance.m_text;
            m_old_display_axis      = textfx_instance.m_display_axis;
            m_old_text_anchor       = textfx_instance.m_text_anchor;
            m_old_text_alignment    = textfx_instance.m_text_alignment;
            m_old_char_size         = textfx_instance.m_character_size;
            m_old_textColour        = textfx_instance.m_textColour;
            m_old_vertexColour      = textfx_instance.m_textColourGradient.Clone();
            m_old_use_gradients     = textfx_instance.m_use_colour_gradient;
            m_old_textColour        = textfx_instance.m_textColour;
            m_old_line_height       = textfx_instance.m_line_height_factor;
            m_old_px_offset         = textfx_instance.m_px_offset;
            m_old_baseline_override = textfx_instance.m_override_font_baseline;
            m_old_font_baseline     = textfx_instance.m_font_baseline_override;
            m_old_max_width         = textfx_instance.m_max_width;

            if (GUI.changed)
            {
                return;
            }


            EditorGUILayout.LabelField("Font Setup Data", EditorStyles.boldLabel);

        #if !UNITY_3_5
            textfx_instance.m_font = EditorGUILayout.ObjectField(new GUIContent("Font (.ttf, .dfont, .otf)", "Your font file to use for this text."), textfx_instance.m_font, typeof(Font), true) as Font;
            if (GUI.changed && textfx_instance.m_font != null)
            {
                textfx_instance.gameObject.GetComponent <Renderer>().material = textfx_instance.m_font.material;
                textfx_instance.m_font_material = textfx_instance.m_font.material;
                textfx_instance.SetText(textfx_instance.m_text);
            }
        #endif

            textfx_instance.m_font_data_file = EditorGUILayout.ObjectField(new GUIContent("Font Data File", "Your Bitmap font text data file."), textfx_instance.m_font_data_file, typeof(TextAsset), true) as TextAsset;
            if (GUI.changed && textfx_instance.m_font_data_file != null && textfx_instance.m_font_material != null)
            {
                // Wipe the old character data hashtable
                textfx_instance.ClearFontCharacterData();
                textfx_instance.SetText(textfx_instance.m_text);
                return;
            }
            textfx_instance.m_font_material = EditorGUILayout.ObjectField(new GUIContent("Font Material", "Your Bitmap font material"), textfx_instance.m_font_material, typeof(Material), true) as Material;
            if (GUI.changed && textfx_instance.m_font_data_file != null && textfx_instance.m_font_material != null)
            {
                // Reset the text with the new material assigned.
                textfx_instance.gameObject.GetComponent <Renderer>().material = textfx_instance.m_font_material;
                textfx_instance.SetText(textfx_instance.m_text);
                return;
            }
            EditorGUILayout.Separator();

            EditorGUILayout.LabelField(new GUIContent("Text", "The text to display."), EditorStyles.boldLabel);
            textfx_instance.m_text = EditorGUILayout.TextArea(textfx_instance.m_text, GUILayout.Width(Screen.width - 25));
            EditorGUILayout.Separator();

            EditorGUILayout.LabelField("Text Settings", EditorStyles.boldLabel);
            EditorGUILayout.BeginHorizontal();

            if (textfx_instance.m_use_colour_gradient)
            {
                EditorGUILayout.BeginVertical();
                EditorGUILayout.BeginHorizontal();
                textfx_instance.m_textColourGradient.top_left  = EditorGUILayout.ColorField("Colour", textfx_instance.m_textColourGradient.top_left);
                textfx_instance.m_textColourGradient.top_right = EditorGUILayout.ColorField(textfx_instance.m_textColourGradient.top_right, GUILayout.Width(53));
                EditorGUILayout.EndHorizontal();
                EditorGUILayout.BeginHorizontal();
                textfx_instance.m_textColourGradient.bottom_left  = EditorGUILayout.ColorField(" ", textfx_instance.m_textColourGradient.bottom_left);
                textfx_instance.m_textColourGradient.bottom_right = EditorGUILayout.ColorField(textfx_instance.m_textColourGradient.bottom_right, GUILayout.Width(53));
                EditorGUILayout.EndHorizontal();
                EditorGUILayout.EndVertical();
            }
            else
            {
                textfx_instance.m_textColour = EditorGUILayout.ColorField("Colour", textfx_instance.m_textColour);                //, GUILayout.Width(260));
            }
            GUILayout.FlexibleSpace();
            EditorGUILayout.LabelField("Use Gradient?", GUILayout.Width(100));
            textfx_instance.m_use_colour_gradient = EditorGUILayout.Toggle(textfx_instance.m_use_colour_gradient, GUILayout.Width(20));
            GUILayout.FlexibleSpace();
            EditorGUILayout.EndHorizontal();

            textfx_instance.m_display_axis       = (TextDisplayAxis)EditorGUILayout.EnumPopup(new GUIContent("Display Axis", "Denotes whether to render the text horizontally or vertically."), textfx_instance.m_display_axis);
            textfx_instance.m_text_anchor        = (TextAnchor)EditorGUILayout.EnumPopup(new GUIContent("Text Anchor", "Defines the anchor point about which the text is rendered"), textfx_instance.m_text_anchor);
            textfx_instance.m_text_alignment     = (TextAlignment)EditorGUILayout.EnumPopup(new GUIContent("Text Alignment", "Defines the alignment of the text, just like your favourite word processor."), textfx_instance.m_text_alignment);
            textfx_instance.m_character_size     = EditorGUILayout.FloatField(new GUIContent("Character Size", "Specifies the size of the text."), textfx_instance.m_character_size);
            textfx_instance.m_line_height_factor = EditorGUILayout.FloatField(new GUIContent("Line Height", "Defines the height of the text lines, based on the tallest line. If value is 2, the lines will be spaced at double the height of the tallest line."), textfx_instance.m_line_height_factor);

            EditorGUILayout.BeginHorizontal();
            textfx_instance.m_override_font_baseline = EditorGUILayout.Toggle(new GUIContent("Override Font Baseline?", "Allows you to manually set a baseline y-offset for the font to be rendered to."), textfx_instance.m_override_font_baseline);
            if (textfx_instance.m_override_font_baseline)
            {
                textfx_instance.m_font_baseline_override = EditorGUILayout.FloatField(new GUIContent("Font Baseline Offset", ""), textfx_instance.m_font_baseline_override);
            }
            EditorGUILayout.EndHorizontal();

            textfx_instance.m_px_offset = EditorGUILayout.Vector2Field("Letter Spacing Offset", textfx_instance.m_px_offset);
            textfx_instance.m_max_width = EditorGUILayout.FloatField(new GUIContent("Max Width", "Defines the maximum width of the text, and breaks the text onto new lines to keep it within this maximum."), textfx_instance.m_max_width);

            if (GUI.changed)
            {
                EditorUtility.SetDirty(textfx_instance);
            }

            if (m_old_char_size != textfx_instance.m_character_size ||
                m_old_textColour != textfx_instance.m_textColour ||
                !m_old_vertexColour.Equals(textfx_instance.m_textColourGradient) ||
                m_old_use_gradients != textfx_instance.m_use_colour_gradient ||
                m_old_display_axis != textfx_instance.m_display_axis ||
                m_old_line_height != textfx_instance.m_line_height_factor ||
                m_old_max_width != textfx_instance.m_max_width ||
                !m_old_text.Equals(textfx_instance.m_text) ||
                m_old_text_alignment != textfx_instance.m_text_alignment ||
                m_old_text_anchor != textfx_instance.m_text_anchor ||
                m_old_px_offset != textfx_instance.m_px_offset ||
                m_old_baseline_override != textfx_instance.m_override_font_baseline ||
                (textfx_instance.m_override_font_baseline && m_old_font_baseline != textfx_instance.m_font_baseline_override))
            {
                textfx_instance.SetText(textfx_instance.m_text);
            }
        }