1
0

FormattedTextPage.axaml.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System.Globalization;
  2. using Avalonia;
  3. using Avalonia.Controls;
  4. using Avalonia.Markup.Xaml;
  5. using Avalonia.Media;
  6. using Avalonia.Media.Immutable;
  7. namespace RenderDemo.Pages
  8. {
  9. public class FormattedTextPage : UserControl
  10. {
  11. public FormattedTextPage()
  12. {
  13. this.InitializeComponent();
  14. }
  15. private void InitializeComponent()
  16. {
  17. AvaloniaXamlLoader.Load(this);
  18. }
  19. public override void Render(DrawingContext context)
  20. {
  21. const string testString = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor";
  22. // Create the initial formatted text string.
  23. var formattedText = new FormattedText(
  24. testString,
  25. CultureInfo.GetCultureInfo("en-us"),
  26. FlowDirection.LeftToRight,
  27. new Typeface("Verdana"),
  28. 32,
  29. Brushes.Black) { MaxTextWidth = 300, MaxTextHeight = 240 };
  30. // Set a maximum width and height. If the text overflows these values, an ellipsis "..." appears.
  31. // Use a larger font size beginning at the first (zero-based) character and continuing for 5 characters.
  32. // The font size is calculated in terms of points -- not as device-independent pixels.
  33. formattedText.SetFontSize(36 * (96.0 / 72.0), 0, 5);
  34. // Use a Bold font weight beginning at the 6th character and continuing for 11 characters.
  35. formattedText.SetFontWeight(FontWeight.Bold, 6, 11);
  36. var gradient = new LinearGradientBrush
  37. {
  38. GradientStops =
  39. new GradientStops { new GradientStop(Colors.Orange, 0), new GradientStop(Colors.Teal, 1) },
  40. StartPoint = new RelativePoint(0,0, RelativeUnit.Relative),
  41. EndPoint = new RelativePoint(0,1, RelativeUnit.Relative)
  42. };
  43. // Use a linear gradient brush beginning at the 6th character and continuing for 11 characters.
  44. formattedText.SetForegroundBrush(gradient, 6, 11);
  45. // Use an Italic font style beginning at the 28th character and continuing for 28 characters.
  46. formattedText.SetFontStyle(FontStyle.Italic, 28, 28);
  47. context.DrawText(formattedText, new Point(10, 0));
  48. var geometry = formattedText.BuildGeometry(new Point(10 + formattedText.Width + 10, 0));
  49. context.DrawGeometry(gradient, null, geometry);
  50. var highlightGeometry = formattedText.BuildHighlightGeometry(new Point(10 + formattedText.Width + 10, 0));
  51. context.DrawGeometry(null, new ImmutablePen(gradient.ToImmutable(), 2), highlightGeometry);
  52. }
  53. }
  54. }