简体   繁体   中英

get the size of UIImageView programmatically

i'm creating an app for iPhone and iPad. and now i would want to retrieve the size of an UIImageView on different phone screen. I have tried with following code:

print("width \(BubbleBackground.frame.size.width)")
print("height \(BubbleBackground.frame.size.height)")
print("width1 \(BubbleBackground.bounds.size.width)")
print("height1 \(BubbleBackground.bounds.size.height)")
print("width2\(BubbleBackground.image!.size.width)")
print("height2\(BubbleBackground.image!.size.height)")

I have tried with the code above, but yet they return me a constant value no matter it is running in iPhone 5, iPhone 6, iPhone 6 plus or iPad. Does anyone have an idea how can i get the image size when it is running on different device?

Your image will be the same size on all devices unless you have set constraints on the image that cause it to resize to fit the current screen size.

Constraints are most often added using Xcode's Interface Builder but can also be added programatically.

Adding constraints using the Interface Builder https://developer.apple.com/library/prerelease/content/documentation/UserExperience/Conceptual/AutolayoutPG/WorkingwithConstraintsinInterfaceBuidler.html#//apple_ref/doc/uid/TP40010853-CH10-SW1

Adding Constraints Programatically https://developer.apple.com/library/prerelease/content/documentation/UserExperience/Conceptual/AutolayoutPG/ProgrammaticallyCreatingConstraints.html

You have to have some constraints to change the imageView frame according to the screen size. Then you can use .layoutIfNeeded() on the UIImageView (BubbleBackground.layoutIfNeeded()) to get its runtime size.

make sure you do this in viewWillAppear or viewDidLayoutSubviews or anytime after these events.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM