GlyphRunPage.xaml.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using Avalonia;
  3. using Avalonia.Controls;
  4. using Avalonia.Markup.Xaml;
  5. using Avalonia.Media;
  6. using Avalonia.Threading;
  7. namespace RenderDemo.Pages
  8. {
  9. public class GlyphRunPage : UserControl
  10. {
  11. private DrawingPresenter _drawingPresenter;
  12. private GlyphTypeface _glyphTypeface = Typeface.Default.GlyphTypeface;
  13. private readonly Random _rand = new Random();
  14. private ushort[] _glyphIndices = new ushort[1];
  15. private float _fontSize = 20;
  16. private int _direction = 10;
  17. public GlyphRunPage()
  18. {
  19. this.InitializeComponent();
  20. }
  21. private void InitializeComponent()
  22. {
  23. AvaloniaXamlLoader.Load(this);
  24. _drawingPresenter = this.FindControl<DrawingPresenter>("drawingPresenter");
  25. DispatcherTimer.Run(() =>
  26. {
  27. UpdateGlyphRun();
  28. return true;
  29. }, TimeSpan.FromSeconds(1));
  30. }
  31. private void UpdateGlyphRun()
  32. {
  33. var c = (uint)_rand.Next(65, 90);
  34. if (_fontSize + _direction > 200)
  35. {
  36. _direction = -10;
  37. }
  38. if (_fontSize + _direction < 20)
  39. {
  40. _direction = 10;
  41. }
  42. _fontSize += _direction;
  43. _glyphIndices[0] = _glyphTypeface.GetGlyph(c);
  44. var scale = (double)_fontSize / _glyphTypeface.DesignEmHeight;
  45. var drawingGroup = new DrawingGroup();
  46. var glyphRunDrawing = new GlyphRunDrawing
  47. {
  48. Foreground = Brushes.Black,
  49. GlyphRun = new GlyphRun(_glyphTypeface, _fontSize, _glyphIndices),
  50. };
  51. drawingGroup.Children.Add(glyphRunDrawing);
  52. var geometryDrawing = new GeometryDrawing
  53. {
  54. Pen = new Pen(Brushes.Black),
  55. Geometry = new RectangleGeometry { Rect = new Rect(glyphRunDrawing.GlyphRun.Size) }
  56. };
  57. drawingGroup.Children.Add(geometryDrawing);
  58. _drawingPresenter.Drawing = drawingGroup;
  59. }
  60. }
  61. }