Show UIImageView smaller than its own size
Having adopted Autolayout and Storyboards, I no longer design screens to be accurate, so when I use images I tend to use a larger image to make it look crisp on iPad, but can be scaled down for smaller iPhones. I am dragging this image into the asset directory.
When I put an image into a view controller in my storyboard, the image wants to be its internal size. I can make it show smaller by setting a certain width proportional to the width of another object, or by constraining it between two other elements.
I am now at a different point in the project where I need to add an image to the code. Although I set a specific height and width for the image border, the image still appears on the screen at its intrinsic size and not where I set it using:
myImage.frame = CGRect(x: self.view.center.x - 50, y: 100, width: 100, height: 100)
Any ideas what I am missing? Thank!
source to share
I want to add imageView
to CenterX
and margin top 100
. And hold the image in a 100, 100 square. This code below will help you.
let imageName = "your image name in resource"
let imageView = UIImageView(frame: CGRectMake(0, 0, 200, 200))
imageView.image = UIImage(named: imageName)
imageView.contentMode = .ScaleAspectFit
imageView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubview(imageView)
// add your constraint
let constTop = NSLayoutConstraint(item: imageView, attribute:.Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1, constant: 100)
// var constLeading = NSLayoutConstraint(item: imageView, attribute: .Leading, relatedBy: .Equal, toItem: self.view, attribute: .Leading, multiplier: 1, constant: self.view.center.x - 50)
var constCenterX = NSLayoutConstraint(item: imageView, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0);
var constWidth = NSLayoutConstraint(item: imageView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1, constant: 100);
var constHight = NSLayoutConstraint(item: imageView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: 100);
imageView.addConstraints([constHight, constWidth])
self.view.addConstraints([constTop, constCenterX])
Hope this helps!
source to share
You need to set the UIImageView contentMode
, which is actually a property UIView
:
If you take the mock code, I hope you do it in the right place ... by overriding layoutSubviews()
, and if needed to be triggered setNeedsLayout()
by an external event, the event fires on the parent view.
Lots of handshakes and customization if needed in code.
source to share