FormattedTextPage.axaml.cs 2.3 KB

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