I want my UIImageView to grow or shrink depending on the size of what the actual image it\'s displaying is. But I want it to stay vertically centered and 10pts
If anyone comes here wanting a simple copy+paste for Xamarin heres @algal's code (with some of @alexander's changes) converted to .Net
Also I've changed it to constrain the Height based on the Width + Aspect Ratio as that fit all of my use cases.
///
/// UIImage view that will set the height correct based on the current
/// width and the aspect ratio of the image.
/// https://stackoverflow.com/a/42654375/9829321
///
public class UIAspectFitImageView : UIImageView
{
private NSLayoutConstraint _heightConstraint;
public override UIImage Image
{
get => base.Image;
set
{
base.Image = value;
UpdateAspectRatioConstraint();
}
}
public UIAspectFitImageView()
=> Setup();
public UIAspectFitImageView(UIImage image) : base(image)
=> Setup();
public UIAspectFitImageView(NSCoder coder) : base(coder)
=> Setup();
public UIAspectFitImageView(CGRect frame) : base(frame)
=> Setup();
public UIAspectFitImageView(UIImage image, UIImage highlightedImage) : base(image, highlightedImage)
=> Setup();
private void Setup()
{
ContentMode = UIViewContentMode.ScaleAspectFit;
UpdateAspectRatioConstraint();
}
private void UpdateAspectRatioConstraint()
{
if (Image != null && Image.Size.Width != 0)
{
var aspectRatio = Image.Size.Height / Image.Size.Width;
if (_heightConstraint?.Multiplier != aspectRatio)
{
if (_heightConstraint != null)
{
RemoveConstraint(_heightConstraint);
_heightConstraint.Dispose();
_heightConstraint = null;
}
_heightConstraint = HeightAnchor.ConstraintEqualTo(WidthAnchor, aspectRatio);
_heightConstraint.Priority = 1000;
_heightConstraint.Active = true;
AddConstraint(_heightConstraint);
}
}
}
}