using System; using Avalonia.Metadata; namespace Avalonia.Media { /// /// An that uses a for content. /// public class DrawingImage : AvaloniaObject, IImage, IAffectsRender { public DrawingImage() { } public DrawingImage(Drawing drawing) { Drawing = drawing; } /// /// Defines the property. /// public static readonly StyledProperty DrawingProperty = AvaloniaProperty.Register(nameof(Drawing)); /// public event EventHandler? Invalidated; /// /// Gets or sets the drawing content. /// [Content] public Drawing? Drawing { get => GetValue(DrawingProperty); set => SetValue(DrawingProperty, value); } /// public Size Size => Drawing?.GetBounds().Size ?? default; /// void IImage.Draw( DrawingContext context, Rect sourceRect, Rect destRect) { var drawing = Drawing; if (drawing == null) { return; } var bounds = drawing.GetBounds(); var scale = Matrix.CreateScale( destRect.Width / sourceRect.Width, destRect.Height / sourceRect.Height); var translate = Matrix.CreateTranslation( -sourceRect.X + destRect.X - bounds.X, -sourceRect.Y + destRect.Y - bounds.Y); using (context.PushClip(destRect)) using (context.PushTransform(translate * scale)) { Drawing?.Draw(context); } } /// protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == DrawingProperty) { RaiseInvalidated(EventArgs.Empty); } } /// /// Raises the event. /// /// The event args. protected void RaiseInvalidated(EventArgs e) => Invalidated?.Invoke(this, e); } }