1
0

GlyphRunPage.xaml.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 Image _imageControl;
  12. private GlyphTypeface _glyphTypeface = Typeface.Default.GlyphTypeface;
  13. private readonly Random _rand = new Random();
  14. private ushort[] _glyphIndices = new ushort[1];
  15. private char[] _characters = new char[1];
  16. private float _fontSize = 20;
  17. private int _direction = 10;
  18. public GlyphRunPage()
  19. {
  20. this.InitializeComponent();
  21. }
  22. private void InitializeComponent()
  23. {
  24. AvaloniaXamlLoader.Load(this);
  25. _imageControl = this.FindControl<Image>("imageControl");
  26. _imageControl.Source = new DrawingImage();
  27. DispatcherTimer.Run(() =>
  28. {
  29. UpdateGlyphRun();
  30. return true;
  31. }, TimeSpan.FromSeconds(1));
  32. }
  33. private void UpdateGlyphRun()
  34. {
  35. var c = (char)_rand.Next(65, 90);
  36. if (_fontSize + _direction > 200)
  37. {
  38. _direction = -10;
  39. }
  40. if (_fontSize + _direction < 20)
  41. {
  42. _direction = 10;
  43. }
  44. _fontSize += _direction;
  45. _glyphIndices[0] = _glyphTypeface.GetGlyph(c);
  46. _characters[0] = c;
  47. var scale = (double)_fontSize / _glyphTypeface.DesignEmHeight;
  48. var drawingGroup = new DrawingGroup();
  49. var glyphRunDrawing = new GlyphRunDrawing
  50. {
  51. Foreground = Brushes.Black,
  52. GlyphRun = new GlyphRun(_glyphTypeface, _fontSize, _characters, _glyphIndices)
  53. };
  54. drawingGroup.Children.Add(glyphRunDrawing);
  55. var geometryDrawing = new GeometryDrawing
  56. {
  57. Pen = new Pen(Brushes.Black),
  58. Geometry = new RectangleGeometry { Rect = new Rect(glyphRunDrawing.GlyphRun.Size) }
  59. };
  60. drawingGroup.Children.Add(geometryDrawing);
  61. (_imageControl.Source as DrawingImage).Drawing = drawingGroup;
  62. }
  63. }
  64. }