GlyphRunPage.xaml.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. BaselineOrigin = new Point(0, -_glyphTypeface.Ascent * scale)
  51. };
  52. drawingGroup.Children.Add(glyphRunDrawing);
  53. var geometryDrawing = new GeometryDrawing
  54. {
  55. Pen = new Pen(Brushes.Black),
  56. Geometry = new RectangleGeometry { Rect = glyphRunDrawing.GlyphRun.Bounds }
  57. };
  58. drawingGroup.Children.Add(geometryDrawing);
  59. _drawingPresenter.Drawing = drawingGroup;
  60. }
  61. }
  62. }