简体   繁体   English

以编程方式获取UIImageView的大小

[英]get the size of UIImageView programmatically

i'm creating an app for iPhone and iPad. 我正在为iPhone和iPad创建一个应用程序。 and now i would want to retrieve the size of an UIImageView on different phone screen. 现在我想在不同的手机屏幕上检索UIImageView的大小。 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. 我已经尝试了上面的代码,但是无论它们在iPhone 5,iPhone 6,iPhone 6 plus或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. 约束通常是使用Xcode的Interface Builder添加的,但是也可以通过编程添加。

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 使用界面生成器添加约束 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 以编程方式添加约束 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. 您必须具有一些约束条件才能根据屏幕尺寸更改imageView框架。 Then you can use .layoutIfNeeded() on the UIImageView (BubbleBackground.layoutIfNeeded()) to get its runtime size. 然后,您可以在UIImageView (BubbleBackground.layoutIfNeeded())上使用.layoutIfNeeded() )来获取其运行时大小。

make sure you do this in viewWillAppear or viewDidLayoutSubviews or anytime after these events. 请确保您在viewWillAppearviewDidLayoutSubviews或在这些事件发生后的任何时候执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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