RenderTargetBitmapPage.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System.Diagnostics;
  2. using Avalonia;
  3. using Avalonia.Controls;
  4. using Avalonia.LogicalTree;
  5. using Avalonia.Media;
  6. using Avalonia.Media.Imaging;
  7. using Avalonia.Threading;
  8. namespace RenderDemo.Pages
  9. {
  10. public class RenderTargetBitmapPage : Control
  11. {
  12. private RenderTargetBitmap _bitmap;
  13. protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
  14. {
  15. _bitmap = new RenderTargetBitmap(new PixelSize(200, 200), new Vector(96, 96));
  16. base.OnAttachedToLogicalTree(e);
  17. }
  18. protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
  19. {
  20. _bitmap.Dispose();
  21. _bitmap = null;
  22. base.OnDetachedFromLogicalTree(e);
  23. }
  24. readonly Stopwatch _st = Stopwatch.StartNew();
  25. public override void Render(DrawingContext context)
  26. {
  27. using (var ctx = _bitmap.CreateDrawingContext())
  28. using (ctx.PushTransform(Matrix.CreateTranslation(-100, -100)
  29. * Matrix.CreateRotation(_st.Elapsed.TotalSeconds)
  30. * Matrix.CreateTranslation(100, 100)))
  31. {
  32. ctx.FillRectangle(Brushes.Fuchsia, new Rect(50, 50, 100, 100));
  33. }
  34. context.DrawImage(_bitmap,
  35. new Rect(0, 0, 200, 200),
  36. new Rect(0, 0, 200, 200));
  37. Dispatcher.UIThread.Post(InvalidateVisual, DispatcherPriority.Background);
  38. base.Render(context);
  39. }
  40. }
  41. }