// Copyright (c) The Perspex Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using Perspex.Media; using Perspex.Media.Imaging; namespace Perspex.Controls { /// /// Displays a image. /// public class Image : Control { /// /// Defines the property. /// public static readonly StyledProperty SourceProperty = PerspexProperty.Register(nameof(Source)); /// /// Defines the property. /// public static readonly StyledProperty StretchProperty = PerspexProperty.Register(nameof(Stretch), Stretch.Uniform); static Image() { AffectsRender(SourceProperty); AffectsRender(StretchProperty); } /// /// Gets or sets the bitmap image that will be displayed. /// public IBitmap Source { get { return GetValue(SourceProperty); } set { SetValue(SourceProperty, value); } } /// /// Gets or sets a value controlling how the image will be stretched. /// public Stretch Stretch { get { return (Stretch)GetValue(StretchProperty); } set { SetValue(StretchProperty, value); } } /// /// Renders the control. /// /// The drawing context. public override void Render(DrawingContext context) { var source = Source; if (source != null) { Rect viewPort = new Rect(Bounds.Size); Size sourceSize = new Size(source.PixelWidth, source.PixelHeight); Vector scale = Stretch.CalculateScaling(Bounds.Size, sourceSize); Size scaledSize = sourceSize * scale; Rect destRect = viewPort .CenterIn(new Rect(scaledSize)) .Intersect(viewPort); Rect sourceRect = new Rect(sourceSize) .CenterIn(new Rect(destRect.Size / scale)); context.DrawImage(source, 1, sourceRect, destRect); } } /// /// Measures the control. /// /// The available size. /// The desired size of the control. protected override Size MeasureOverride(Size availableSize) { var source = Source; if (source != null) { Size sourceSize = new Size(source.PixelWidth, source.PixelHeight); if (double.IsInfinity(availableSize.Width) || double.IsInfinity(availableSize.Height)) { return sourceSize; } else { return Stretch.CalculateSize(availableSize, sourceSize); } } else { return new Size(); } } } }