2using System.Runtime.CompilerServices;
3using System.Text.RegularExpressions;
77 private string _text =
string.Empty;
78 private readonly List<string> _lines =
new();
79 private float _lineHeight;
80 private bool _layoutDirty =
true;
82 private SKColor _foreColor = SKColors.White;
83 private SKColor _backColor = SKColors.Transparent;
85 private float _fontSize = 16f;
86 private float? _minFontSize =
null;
87 private SKTypeface? _typeface =
null;
89 private bool _useOutline =
false;
90 private bool _wrapText =
true;
91 private int? _maxLines =
null;
93 private bool _useShadow =
false;
94 private float _shadowDx = 2f, _shadowDy = 2f;
95 private byte _shadowAlpha = 128;
96 private float _shadowBlurSigma = 1.5f;
98 private SKTextAlign _hAlign = SKTextAlign.Left;
100 private float _verticalScrollOffsetPx;
101 private float _verticalScrollEndPaddingPx;
104 private bool _pulseTextEnabled;
105 private SKColor _pulseFrom, _pulseTo;
106 private float _pulsePeriodSec = 1f;
110 private long? _pulseLastTick;
111 private float _timeSec;
114 private long _revealLastTick;
116 private int _revealCharCount;
117 private int _revealTargetCharCount;
118 private float _revealRate;
119 private float _revealAccum;
122 private int[]? _wordEndCharIndexes;
123 private int _wordIndex;
126 private bool _pauseEnabled =
true;
127 private float _pauseLongSec = 0.25f;
128 private float _pauseShortSec = 0.10f;
131 private SKColor _resolvedForeColor;
148 Rectangle? screenBounds,
149 Rectangle? worldBounds,
150 string? nickname =
null)
160 _resolvedForeColor = _foreColor;
175 Rectangle worldBounds,
176 string? nickname =
null)
183 worldBounds: worldBounds,
198 Rectangle screenBounds,
199 string? nickname =
null)
205 screenBounds: screenBounds,
235 get => _verticalScrollOffsetPx;
238 if (!
float.IsFinite(value) || value < 0f)
239 throw new ArgumentOutOfRangeException(nameof(value));
241 if (Math.Abs(_verticalScrollOffsetPx - value) < 0.001f)
244 _verticalScrollOffsetPx = value;
258 get => _verticalScrollEndPaddingPx;
261 if (!
float.IsFinite(value) || value < 0f)
262 throw new ArgumentOutOfRangeException(nameof(value));
264 if (Math.Abs(_verticalScrollEndPaddingPx - value) < 0.001f)
267 _verticalScrollEndPaddingPx = value;
283 float innerHeight = Math.Max(0f, bounds.Height -
VerticalPadding * 2f);
285 _typeface ??= SKTypeface.Default;
287 using var paint =
new SKPaint
289 Typeface = _typeface,
290 TextSize = _fontSize,
294 float fontSize = _fontSize;
295 float minimumFontSize = _minFontSize ?? 0f;
299 paint.TextSize = fontSize;
300 RebuildLayout(paint, innerWidth);
302 int drawableLines = _maxLines.HasValue
303 ? Math.Min(_lines.Count, _maxLines.Value)
306 float contentHeight = drawableLines * _lineHeight;
307 bool exceedsHeight = contentHeight > innerHeight;
308 bool exceedsWidth = _lines.Any(line => paint.MeasureText(line) > innerWidth);
310 if (_minFontSize.HasValue &&
311 (exceedsHeight || exceedsWidth) &&
312 fontSize > minimumFontSize)
314 fontSize = Math.Max(minimumFontSize, fontSize - 1f);
318 float maximumOffset = Math.Max(0f, contentHeight - innerHeight);
320 if (maximumOffset > 0f)
326 return maximumOffset;
336 public TextBlock
SetPadding(
float horizontal,
float vertical)
338 if (!
float.IsFinite(horizontal) || horizontal < 0f)
339 throw new ArgumentOutOfRangeException(nameof(horizontal));
341 if (!
float.IsFinite(vertical) || vertical < 0f)
342 throw new ArgumentOutOfRangeException(nameof(vertical));
358 if (size.Width <= 0 || size.Height <= 0)
359 throw new ArgumentOutOfRangeException(nameof(size), size,
"Text block size must be positive.");
380 _text = text ??
string.Empty;
386 _revealCharCount = _text.Length;
391 _revealTargetCharCount = _text.Length;
394 if (_revealCharCount > _revealTargetCharCount)
395 _revealCharCount = _revealTargetCharCount;
414 public TextBlock
SetFont(SKTypeface typeface,
float size,
float? minSize =
null)
416 _typeface = typeface;
418 _minFontSize = minSize;
434 _resolvedForeColor = fg;
500 float blurSigma = 1.5f)
504 _shadowAlpha = alpha;
505 _shadowBlurSigma = MathF.Max(0f, blurSigma);
517 _useOutline = enable;
542 _maxLines = maxLines;
561 bool triangle =
false)
563 _pulseTextEnabled = enabled;
564 _pulseFrom = from.ToSKColor();
565 _pulseTo = to.ToSKColor();
566 _pulsePeriodSec = MathF.Max(0.0001f, periodSec);
570 _resolvedForeColor = _foreColor;
581 _pulseTextEnabled =
false;
582 _resolvedForeColor = _foreColor;
597 float charsPerSecond,
598 int? maxChars =
null,
599 bool enablePauses =
true,
600 float longPauseSec = 0.25f,
601 float shortPauseSec = 0.10f)
604 _revealRate = MathF.Max(0f, charsPerSecond);
605 _revealCharCount = 0;
606 _revealTargetCharCount = maxChars.HasValue ? Math.Min(maxChars.Value, _text.Length) : _text.Length;
608 _wordEndCharIndexes =
null;
613 _pauseEnabled = enablePauses;
614 _pauseLongSec = longPauseSec;
615 _pauseShortSec = shortPauseSec;
630 float wordsPerSecond,
631 bool enablePauses =
true,
632 float longPauseSec = 0.25f,
633 float shortPauseSec = 0.10f)
636 _revealRate = MathF.Max(0f, wordsPerSecond);
637 _revealCharCount = 0;
638 _revealTargetCharCount = _text.Length;
644 _wordEndCharIndexes = Regex.Matches(_text,
@"\S+\s*")
645 .Select(m => m.Index + m.Length)
650 _pauseEnabled = enablePauses;
651 _pauseLongSec = longPauseSec;
652 _pauseShortSec = shortPauseSec;
667 _pauseEnabled = enabled;
668 _pauseLongSec = longPauseSec;
669 _pauseShortSec = shortPauseSec;
681 _revealCharCount = Math.Clamp(charCount, 0, _text.Length);
682 _revealTargetCharCount = _text.Length;
694 _revealCharCount = _text.Length;
704 private float PauseFor(
char c)
711 '.' or
'!' or
'?' => _pauseLongSec,
712 ',' or
';' or
':' => _pauseShortSec,
730 if (_pulseLastTick.HasValue)
731 dtPulse = HighResTimer.GetDuration(_pulseLastTick.Value, tick);
733 _pulseLastTick = tick;
735 if (dtPulse > 0f && dtPulse < 1f)
738 if (_pulseTextEnabled)
740 float t = PulseT(_timeSec, _pulsePeriodSec, _pulseWave);
741 var c = LerpColor(_pulseFrom, _pulseTo, t);
743 if (c != _resolvedForeColor)
745 _resolvedForeColor = c;
752 if (_resolvedForeColor != _foreColor)
754 _resolvedForeColor = _foreColor;
762 if (_revealLastTick == 0)
764 _revealLastTick = tick;
768 dtReveal = HighResTimer.GetDuration(_revealLastTick, tick);
769 _revealLastTick = tick;
782 _revealAccum += dtReveal;
784 if (_revealRate > 0f)
786 int step = (int)(_revealAccum * _revealRate);
790 _revealAccum -= step / _revealRate;
792 int old = _revealCharCount;
793 _revealCharCount = Math.Min(_revealCharCount + step, _revealTargetCharCount);
796 for (
int i = old; i < _revealCharCount; i++)
797 _revealAccum -= PauseFor(_text[i]);
803 if (_revealCharCount > old)
805 var revealed = _text.Substring(0, _revealCharCount);
810 if (_revealCharCount >= _revealTargetCharCount)
819 else if (_textRevealMode ==
TextRevealMode.WordsPerSecond && _wordEndCharIndexes is not
null)
821 _revealAccum += dtReveal;
823 if (_revealRate > 0f)
825 int step = (int)(_revealAccum * _revealRate);
829 _revealAccum -= step / _revealRate;
831 int oldCount = _revealCharCount;
833 _wordIndex = Math.Min(_wordIndex + step, _wordEndCharIndexes.Length);
834 _revealCharCount = _wordIndex == 0 ? 0 : _wordEndCharIndexes[_wordIndex - 1];
837 if (_revealCharCount > 0)
838 _revealAccum -= PauseFor(_text[_revealCharCount - 1]);
843 if (_revealCharCount > oldCount)
845 var revealed = _text.Substring(0, _revealCharCount);
849 if (_wordIndex >= _wordEndCharIndexes.Length)
870 var canvas = backbuffer.
Canvas;
871 var rect = destRectScreen.ToSKRect();
873 float zoom = ResolveTextScale(
Mode, RenderContext.Current?.ViewportZoom ?? 1f);
878 float shadowDx = _shadowDx * zoom;
879 float shadowDy = _shadowDy * zoom;
880 float shadowBlur = _shadowBlurSigma * zoom;
881 float outlineWidth = 1.5f * zoom;
884 if (_backColor.Alpha != 0)
886 using var bg =
new SKPaint { Color = _backColor };
887 canvas.DrawRect(rect, bg);
890 _typeface ??= SKTypeface.Default;
893 using var paint =
new SKPaint
895 Typeface = _typeface ?? SKTypeface.Default,
896 TextSize = _fontSize * zoom,
897 Color = _resolvedForeColor,
904 float fontSize = _fontSize * zoom;
905 float minFontSize = _minFontSize.HasValue ? _minFontSize.Value * zoom : 0f;
907 float innerW = Math.Max(0, rect.Width - hPad * 2f);
908 float innerH = Math.Max(0, rect.Height - vPad * 2f);
912 paint.TextSize = fontSize;
915 if (_layoutDirty || zoom != 1f)
916 RebuildLayout(paint, innerW);
918 int drawableLines = _maxLines.HasValue ? Math.Min(_lines.Count, _maxLines.Value) : _lines.Count;
919 float totalH = drawableLines * _lineHeight;
921 bool exceedsHeight = totalH > innerH;
922 bool exceedsWidth = _lines.Any(line => paint.MeasureText(line) > innerW);
924 if (_minFontSize.HasValue &&
925 (exceedsHeight || exceedsWidth) &&
926 fontSize > minFontSize)
928 fontSize = Math.Max(minFontSize, fontSize - 1f);
931 if (fontSize <= minFontSize)
942 ? Math.Clamp(_revealCharCount, 0, _text.Length)
947 List<string> drawLines =
new(_lines.Count);
949 if (visibleChars <= 0)
953 else if (visibleChars >= _text.Length)
955 drawLines.AddRange(_lines);
959 int remaining = visibleChars;
961 foreach (var ln
in _lines)
966 if (ln.Length <= remaining)
969 remaining -= ln.Length;
973 drawLines.Add(ln.Substring(0, remaining));
979 bool wasTruncatedByMaxLines = _maxLines.HasValue && drawLines.Count > _maxLines.Value;
982 int linesToDraw = _maxLines.HasValue ? Math.Min(drawLines.Count, _maxLines.Value) : drawLines.Count;
984 if (linesToDraw > 0 && wasTruncatedByMaxLines)
986 drawLines[linesToDraw - 1] = FitLineWithEllipsis(paint, drawLines[linesToDraw - 1], innerW);
990 var fm = paint.FontMetrics;
991 float baselineShift = -fm.Ascent;
993 float contentH = linesToDraw * _lineHeight;
994 float maximumScrollOffset = Math.Max(0f, contentH - innerH);
996 if (maximumScrollOffset > 0f)
999 float yStart = maximumScrollOffset > 0f
1005 _ => rect.Top + vPad
1008 float scrollOffset = Math.Min(_verticalScrollOffsetPx * zoom, maximumScrollOffset);
1009 yStart -= scrollOffset;
1012 float xAnchorLeft = rect.Left + hPad;
1013 float xAnchorCenter = rect.MidX;
1014 float xAnchorRight = rect.Right - hPad;
1017 canvas.ClipRect(rect);
1021 for (
int i = 0; i < linesToDraw; i++)
1023 var line = drawLines[i];
1025 float x = _hAlign
switch
1027 SKTextAlign.Center => xAnchorCenter,
1028 SKTextAlign.Right => xAnchorRight,
1034 using var shadow = paint.Clone();
1035 shadow.IsStroke =
false;
1037 shadow.MaskFilter = shadowBlur > 0f
1038 ? SKMaskFilter.CreateBlur(SKBlurStyle.Normal, shadowBlur)
1041 shadow.Color =
new SKColor(
1051 y + baselineShift + shadowDy,
1057 using var outline = paint.Clone();
1058 outline.IsStroke =
true;
1059 outline.StrokeWidth = outlineWidth;
1060 outline.Color = SKColors.Black;
1078 if (y > rect.Bottom)
1085 internal static float ResolveTextScale(
DirectDrawingMode mode,
float viewportZoom)
1090 return viewportZoom > 0f ? viewportZoom : 1f;
1093 private void RebuildLayout(SKPaint paint,
float maxWidth)
1097 var fm = paint.FontMetrics;
1100 var paragraphs = _text.Replace(
"\r\n",
"\n").Split(
'\n');
1102 foreach (var para
in paragraphs)
1104 if (
string.IsNullOrEmpty(para))
1106 _lines.Add(
string.Empty);
1116 var words = para.Split(
' ', StringSplitOptions.None);
1117 var current =
string.Empty;
1119 foreach (var word
in words)
1121 string candidate =
string.IsNullOrEmpty(current) ? word : current +
" " + word;
1122 float candidateWidth = paint.MeasureText(candidate);
1124 if (candidateWidth <= maxWidth)
1126 current = candidate;
1131 if (!
string.IsNullOrEmpty(current))
1133 _lines.Add(current);
1134 current =
string.Empty;
1138 if (paint.MeasureText(word) <= maxWidth)
1145 var chunk =
string.Empty;
1147 foreach (
char ch
in word)
1149 string next = chunk + ch;
1151 if (paint.MeasureText(next) <= maxWidth ||
string.IsNullOrEmpty(chunk))
1158 chunk = ch.ToString();
1162 if (!
string.IsNullOrEmpty(chunk))
1166 if (!
string.IsNullOrEmpty(current))
1167 _lines.Add(current);
1170 _layoutDirty =
false;
1173 [MethodImpl(MethodImplOptions.AggressiveInlining)]
1174 private static float PulseT(
float timeSec,
float periodSec,
PulseWave wave)
1176 float phase = (timeSec / periodSec) % 1f;
1179 ? 0.5f * (1f + MathF.Sin(phase * MathF.PI * 2f))
1180 : (phase < 0.5f ? phase * 2f : 1f - (phase - 0.5f) * 2f);
1183 [MethodImpl(MethodImplOptions.AggressiveInlining)]
1184 private static SKColor LerpColor(SKColor a, SKColor b,
float t01)
1186 t01 = Math.Clamp(t01, 0f, 1f);
1187 byte r = (byte)(a.Red + (b.Red - a.Red) * t01);
1188 byte g = (byte)(a.Green + (b.Green - a.Green) * t01);
1189 byte bl = (byte)(a.Blue + (b.Blue - a.Blue) * t01);
1190 byte al = (byte)(a.Alpha + (b.Alpha - a.Alpha) * t01);
1199 private static string FitLineWithEllipsis(SKPaint paint,
string text,
float maxWidth)
1201 const string ellipsis =
"...";
1203 if (
string.IsNullOrEmpty(text))
1206 if (paint.MeasureText(text) <= maxWidth)
1209 float ellipsisWidth = paint.MeasureText(ellipsis);
1211 if (ellipsisWidth > maxWidth)
1212 return string.Empty;
1214 int length = text.Length;
1218 string candidate = text.Substring(0, length).TrimEnd() + ellipsis;
1220 if (paint.MeasureText(candidate) <= maxWidth)
1226 return ellipsisWidth <= maxWidth ? ellipsis :
string.Empty;
1229 #region public readonly properties
1318 #endregion public readonly properties
1350 private readonly
object _eventLock =
new();
1367 base.Dispose(disposing);
View? View
Gets the view to which this direct drawing is attached, or null if the drawing is in scene-layer mode...
long _lastTick
The last engine tick value used for delta-time calculations in Update.
SceneLayer? SceneLayer
Gets the scene layer to which this direct drawing is attached, or null if the drawing is in view mode...
Rectangle WorldBounds
Gets or sets the world-space bounds of this direct drawing in pixels.
DirectDrawingMode Mode
Gets the drawing mode that determines how this direct drawing is positioned and transformed.
Rectangle ScreenBounds
Gets or sets the screen-space bounds of this direct drawing in pixels.
DirectDrawingMovableBase(RenderSurfaceHostBase renderSurfaceHost, DirectDrawingMode mode, SceneLayer? sceneLayer, View? view, Rectangle? screenBounds, Rectangle? worldBounds, string? name=null)
Initializes a new instance of the DirectDrawingMovableBase class with integrated movement capabilitie...
TextBlock SetShadow(float dx, float dy, byte alpha=128, float blurSigma=1.5f)
Configures the drop shadow effect for text rendering.
TextBlock UseOutline(bool enable=true)
Enables or disables a 1-pixel outline stroke around the text glyphs.
float PunctuationPauseShortSec
Gets the short punctuation pause duration (seconds) used for ',', ';', ':'.
float ShadowDy
Gets the vertical shadow offset (in pixels).
PulseWave
Selects the waveform used by PulseColor(Color, Color, float, bool, bool).
@ Triangle
Triangle wave: linear fade-in/out between colors.
@ Sine
Sine wave: smooth continuous pulse between colors.
SKColor ResolvedForeColor
Gets the currently resolved (effective) foreground color used for drawing.
float PulsePeriodSec
Gets the pulse period in seconds.
TextBlock(RenderSurfaceHostBase renderSurfaceHost, SceneLayer sceneLayer, View? view, Rectangle worldBounds, string? nickname=null)
Creates a new TextBlock that draws in world space on the specified scene layer.
TextBlock SetColors(Color fg, Color bg)
Sets the foreground (text) and background colors using System.Drawing colors.
float ShadowBlurSigma
Gets the blur radius for the shadow (sigma, in pixels).
SKColor PulseFrom
Gets the starting color for the pulse effect.
VerticalAlign AlignVert
Gets the vertical alignment used when drawing lines.
float HorizontalPadding
Gets or sets the horizontal padding (in pixels) on both left and right sides of the text.
float PunctuationPauseLongSec
Gets the long punctuation pause duration (seconds) used for '.', '!', '?'.
TextBlock SetFont(SKTypeface typeface, float size, float? minSize=null)
Sets the font face and size (and optional minimum size for auto-shrink).
bool WrapText
Gets a value indicating whether word wrapping is enabled.
TextBlock(RenderSurfaceHostBase renderSurfaceHost, View view, Rectangle screenBounds, string? nickname=null)
Creates a new TextBlock that draws in screen space relative to a view.
SKColor ForeColor
Gets the configured foreground (text) color.
TextBlock EnableWrapping(bool enable=true)
Enables or disables word wrapping when laying out paragraphs.
TextBlock SetAlignment(SKTextAlign h, VerticalAlign v)
Sets the horizontal and vertical alignment used when drawing the laid-out lines within the bounds.
float? MinFontSize
Gets the optional minimum font size used by auto-shrink (or null if disabled).
TextBlock SetPadding(float horizontal, float vertical)
Sets symmetric horizontal and vertical padding and invalidates cached layout.
SKTypeface? TypeFace
Gets the configured typeface (or null to use SKTypeface.Default).
TextBlock StartWordReveal(float wordsPerSecond, bool enablePauses=true, float longPauseSec=0.25f, float shortPauseSec=0.10f)
Begins a word-by-word reveal. Words are detected by \S+\s* and include their trailing whitespace/punc...
VerticalAlign
Vertical alignment options for multi-line text within the control's bounds.
@ Bottom
Align text to the bottom of the inner content area.
@ Center
Center text vertically within the inner content area.
@ Top
Align text to the top of the inner content area.
SKColor BackColor
Gets the configured background color.
TextBlock UseShadow(bool enable=true)
Enables or disables drawing a drop shadow behind the text (parameters are configured via SetShadow(fl...
TextBlock SetColors(SKColor fg, SKColor bg)
Sets the foreground (text) and background colors using Skia colors.
float LineSpacingMultiplier
Gets or sets a scale factor applied to the computed line height (1.0 = natural spacing).
override void OnDraw(BackbufferBase backbuffer, RectangleF destRectScreen)
Draws the laid-out text block contents into the destination rectangle.
bool PulseTextEnabled
Gets a value indicating whether color pulsing is enabled.
float VerticalScrollEndPaddingPx
Gets or sets extra scrollable space after the final laid-out line.
Action< string >? TextRevealComplete
Raised once when the reveal completes. Argument is the full text content. Note: when the final chunk ...
override void Dispose(bool disposing)
Releases managed resources used by the text block.
TextBlock RevealSetCount(int charCount)
Sets the currently revealed character count directly (manual mode).
float FontSize
Gets the requested font size (before any auto-shrink adjustments).
PulseWave PulseWaveValue
Gets the pulse waveform currently in use.
byte ShadowAlpha
Gets the shadow opacity (0-255).
float MeasureMaximumVerticalScrollOffsetPx()
Measures the maximum vertical scroll offset required to expose all currently laid-out text.
bool OutlineEnabled
Gets a value indicating whether an outline stroke is enabled.
SKColor PulseTo
Gets the ending color for the pulse effect.
TextRevealMode TextRevealModeValue
Gets the active text reveal mode.
bool ShadowEnabled
Gets a value indicating whether a drop shadow is enabled.
int? MaxLines
Gets the optional maximum number of lines to draw (or null for no limit).
float ShadowDx
Gets the horizontal shadow offset (in pixels).
TextBlock SetPunctuationPauses(bool enabled, float longPauseSec=0.25f, float shortPauseSec=0.10f)
Configures punctuation pause behavior used by the current or next reveal animation.
float VerticalPadding
Gets or sets the vertical padding (in pixels) on both top and bottom sides of the text.
List< string > Lines
Gets the laid-out lines (after wrapping and paragraph processing).
TextBlock StopColorPulse()
Stops text color pulsing and restores the base foreground color.
float VerticalScrollOffsetPx
Gets or sets the vertical text-content scroll offset in native pixels.
TextRevealMode
Describes the mode used for revealing text over time.
@ CharactersPerSecond
Reveal advances by characters per second.
@ None
No reveal is active; all text is shown.
@ ManualCount
Reveal amount is controlled directly via RevealSetCount(int).
@ WordsPerSecond
Reveal advances by words per second.
TextBlock RevealStop()
Stops any active reveal animation and shows the full text immediately.
SKTextAlign AlignHoriz
Gets the horizontal alignment used when drawing lines.
Action< string >? TextRevealed
Raised whenever the revealed text portion advances. The argument is the cumulative text currently rev...
TextBlock SetText(string text)
Sets the current text content and rebuilds layout as needed. If no reveal animation is active,...
float LineHeight
Gets the measured line height (in pixels) used for drawing.
TextBlock PulseColor(Color from, Color to, float periodSec, bool enabled=true, bool triangle=false)
Animates the text color between from and to over periodSec seconds.
string Text
Gets the current raw text content.
TextBlock SetSize(Size size)
Sets the text-block size while preserving its current position and invalidates cached layout.
TextBlock SetMaxLines(int? maxLines)
Sets a maximum number of lines to draw. If null, all laid-out lines are drawn.
override void Update(long tick)
Advances internal animations (pulse, typewriter/word reveal) based on the current tick,...
float TextRevealRate
Gets the configured reveal rate (characters/sec or words/sec depending on mode).
bool PuctuationPauseEnabled
Gets a value indicating whether punctuation pauses are enabled.
TextBlock StartTypewriter(float charsPerSecond, int? maxChars=null, bool enablePauses=true, float longPauseSec=0.25f, float shortPauseSec=0.10f)
Begins a character-by-character reveal (typewriter effect).
Represents a base class for managing a graphical backbuffer, and is the in-memory surface where rende...
SKCanvas Canvas
Gets the SkiaSharp canvas used for drawing operations on this backbuffer.
Represents a base class for hosting a render surface, providing functionality for managing rendering ...
DirectDrawingMode
Specifies where direct drawing operations are applied within the rendering pipeline.
@ View
Performs direct drawing at the view level using screen-space coordinates.