RenderTargetBitmapPage.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. using Avalonia.Visuals.Media.Imaging;
  9. namespace RenderDemo.Pages
  10. {
  11. public class RenderTargetBitmapPage : Control
  12. {
  13. private RenderTargetBitmap _bitmap;
  14. protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
  15. {
  16. _bitmap = new RenderTargetBitmap(new PixelSize(200, 200), new Vector(96, 96));
  17. base.OnAttachedToLogicalTree(e);
  18. }
  19. protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
  20. {
  21. _bitmap.Dispose();
  22. _bitmap = null;
  23. base.OnDetachedFromLogicalTree(e);
  24. }
  25. readonly Stopwatch _st = Stopwatch.StartNew();
  26. public override void Render(DrawingContext context)
  27. {
  28. using (var ctxi = _bitmap.CreateDrawingContext(null))
  29. using(var ctx = new DrawingContext(ctxi, false))
  30. using (ctx.PushPostTransform(Matrix.CreateTranslation(-100, -100)
  31. * Matrix.CreateRotation(_st.Elapsed.TotalSeconds)
  32. * Matrix.CreateTranslation(100, 100)))
  33. {
  34. ctxi.Clear(default);
  35. ctx.FillRectangle(Brushes.Fuchsia, new Rect(50, 50, 100, 100));
  36. }
  37. context.DrawImage(_bitmap,
  38. new Rect(0, 0, 200, 200),
  39. new Rect(0, 0, 200, 200));
  40. Dispatcher.UIThread.Post(InvalidateVisual, DispatcherPriority.Background);
  41. base.Render(context);
  42. }
  43. }
  44. }