Autolayout Aspect Ratio for Uiimageview/Uiview

Autolayout aspect ratio for UIImageView / UIView

As I understood your problem is that you want to control how much the image will be increased in each different screen size. You can control everything. What you need to do is to assign an equals width constraint on your image. Preferable on image's width. The relation will be with the superview and then you can change the relation by adding your own Multiplier.

What you need to do exactly:

1) Select your image view.

2) Hold down the control key. While you are holding it, drag your mouse from the image view to the outer view.

3) Select 'Equals width'.

4) Double click on your constraint in the 'Constraints' tab.

5) Ensure that the image view is presented as the first item, if not click on the first item and select 'Reverse first and second item'.

6) Play with the multiplier until you are satisfied with the result on the preview screen.

Interface Builder: automatically set aspect ratio for UIImageView when using Aspect Fit?

I believe you'll have to do this programmatically. If you don't want to do it view by view, just define some subclass (which you can specify as the base class in IB) that sets constraints programmatically

class RatioImageView: UIImageView {

private var ratioConstraint: NSLayoutConstraint?

override var image: UIImage? {
didSet { updateRatioConstraint() }
}

override func didMoveToSuperview() {
super.didMoveToSuperview()

updateRatioConstraint()
}

private func updateRatioConstraint() {
if let ratioConstraint = ratioConstraint {
removeConstraint(ratioConstraint)
}

guard superview != nil else { return }

let ratio: CGFloat
if let image = image {
ratio = image.size.width / image.size.height
} else {
ratio = 1
}

ratioConstraint = widthAnchor.constraint(equalTo: heightAnchor, multiplier: ratio)
ratioConstraint?.isActive = true
}
}

This does it on an image view, but you could presumably do the same with UIButton or whatever, too.


Or in another variation of the theme, you could control this with intrinsic size, where perhaps you explicitly set the height (and because this is @IBInspectable, you can do this right in IB), and it will return the intrinsic size scaled for that height:

@IBDesignable
class RatioImageView: UIImageView {

@IBInspectable var height: CGFloat = 0

override var intrinsicContentSize: CGSize {
guard let image = image else { return .zero }
guard height > 0 else { return image.size }

let ratio = image.size.width / image.size.height

return CGSize(width: height * ratio, height: height)
}

}

constrain for uiimageview to keep aspect ratio and expand based on device size

Select your image view and it's super view together and give equal width constraint,

then select that equal width constraint from size inspector, and reduce its multiplier until you get your desired width!

Now select your image view and give aspect ratio constraint!

And finally give position constraint for x and y position!

In your case center x and center y with it's super view I think!

And your imageview will increase or decrease with device width and will remains square always!

And You should set dynamic corner radius(half of width or height of your imageview) in layoutSubviews method of tableviewcell's class as you need rounded imageview and your size is dynamic!

How to keep UIIMage aspect ratio and side padding width and prevent the height from exceeding the parent view height

You want "a little padding" ... I'll use 20-pts for this example, and assume you mean you want at least 20-pts on each side and top and bottom.

You can do this using >= values, plus width and height constraints with Priority set to less-than 1000.

Take a look at these constraints:

Sample Image

We've set the aspect-ratio to 36:64 (that's the same as 0.36:0.64 but makes a little more sense).

We've set top, bottom, leading and trailing all to >= 20 ... that prevents any side from getting closer than 20-pts to the edges (the safe-area edges).

We've set centerX and centerY constraints, to keep the view centered.

The final step is to set the image view's width and height equal to the width and height of the view's safe-area, but we give each one a Priority of 750.

In plain language, this says: make the imageView as wide and tall as possible, without violating the edge-padding, and always keep the aspect-ratio.

Here's how it looks on a XS:

Sample Image

on an 8:

Sample Image

and on a 4S:

Sample Image

and, here's how it looks on an 8 rotated to Landscape orientation:

Sample Image

How to hide an UIImageView with Aspect Ratio autolayout constraint?

The only solution that I see here is - when you need to hide it, than you should:

1) Get width of you view
2) set aspect ratio constraint active = NO 3) create width constraint from value getted before 4) create height constraint with constant = 0 5) add this two constraints(if doing from code)
6) Animate

As well you can create width and height constraints in builder with aspect ratio constraint and just manipulate with property active

UIImageView with auto-layout and max size keeping aspect ratio

You'll need three constraints here. One that maintains the aspect ratio, one that makes sure the width is no larger than the maximum, and one that makes sure the height is no larger than the maximum. As of August 2016, Interface Builder does not support constraints referencing other constraints, so – at a minimum – the aspect ratio constraint must be done in code.

The aspect ratio is the only one that takes any thinking. Let V_w and V_h be the width and height, respectively, of your image view. Let I_w and I_h be the width and height, respectively, of your image. Then, to maintain the image's aspect ratio, the following equation must remain true:

V_w / V_h = I_w / I_h

Or, equivalently:

V_w = (I_w / I_h) * V_h

Ok, looking good. Let's write some code. In this code, I assume you have MAX_HEIGHT and MAX_WIDTH defined earlier. Note that this code must target iOS 9.0 or later. If you're targeting an earlier version of iOS, see the block below.

// Constrain the desired aspect ratio
[imageView.widthAnchor constraintEqualToAnchor:imageView.heightAnchor
multiplier:aspectRatioMult].active = YES;

// Constrain height
[imageView.heightAnchor constraintLessThanOrEqualToConstant:MAX_HEIGHT].active = YES;

// Constrain width
[imageView.widthAnchor constraintLessThanOrEqualToConstant:MAX_WIDTH].active = YES;

For code targeting iOS versions before 9.0, NSLayoutAnchor is not available. Instead, you'll have to make due with NSLayoutConstraint.

CGFloat aspectRatioMult = (imageView.image.size.width / imageView.image.size.height);

// Constrain the desired aspect ratio
[imageView addConstraint:
[NSLayoutConstraint constraintWithItem:imageView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:imageView
attribute:NSLayoutAttributeHeight
multiplier:aspectRatioMult
constant:0]];

// Constrain height
[imageView addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"V:[imageView(<=max)]"
options:0
metrics:@{@"max" : @(MAX_HEIGHT)}
views:@{@"imageView" : imageView}]];

// Constrain width
[imageView addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:[imageView(<=max)]"
options:0
metrics:@{@"max" : @(MAX_WIDTH)}
views:@{@"imageView" : imageView}]];

Storyboard and AutoLayout: how to set UIView to use same aspect ratio as device?

The UIView in UIViewController has always the same ratio.
Unrelated to a UIViewController you need to determine the screen you want to relate to. (There can be more than 1 during run time)

UIApplication.shared.windows.first?.screen.bounds

would give you the bounds of the first window during runtime.

Autolayout in this case requires a view you can relate to.

You could have a same width and height constraint on your view and the topmostview. (Superview)

How can I set aspect ratio constraints programmatically in iOS?

Like this. Try once.

[self.yourview setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.yourview addConstraint:[NSLayoutConstraint
constraintWithItem:self.yourview
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:self.yourview
attribute:NSLayoutAttributeWidth
multiplier:(self.yourview.frame.size.height / self.yourview.frame.size.width)
constant:0]];

or in the place of (self.yourview.frame.size.height / self.yourview.frame.size.width) you can use any float value.
Thanks.

Swift 3.0 -

self.yourview!.translatesAutoresizingMaskIntoConstraints = false
self.yourview!.addConstraint(NSLayoutConstraint(item: self.yourview!,
attribute: NSLayoutAttribute.height,
relatedBy: NSLayoutRelation.equal,
toItem: self.yourview!,
attribute: NSLayoutAttribute.width,
multiplier: self.yourview.frame.size.height / self.yourview.frame.size.width,
constant: 0))

With Auto Layout, how do I make a UIImageView's size dynamic depending on the image?

The image view's intrinsic size is already dependent on the size of the image. Your assumptions (and constraints are correct).

However, if you've set up your image view in interface builder and have not provided it with an image, then the layout system (interface builder) won't know how big your image view is supposed to be at compile time. Your layout is ambiguous because your image view could be many sizes. This is what throws the errors.

Once you set your image view's image property, then the image view's intrinsic size is defined by the size of the image. If you're setting the view at runtime, then you can do exactly what Anna mentioned and provide interface builder with a "placeholder" intrinsic size in the property inspector of the image view. This tells interface builder, "use this size for now, I'll give you a real size later". The placeholder constraints are ignored at runtime.

Your other option is to assign the image to the image view in interface builder directly (but I assume your images are dynamic, so this won't work for you).



Related Topics



Leave a reply



Submit