我在
Swift故事板中全屏使用’Aspect Fit’模式imageview.实际图像很好地保持比例.问题是我无法在运行时获得实际的图像宽度/高度.
当我使用imageview.frame.size.width时,它会按预期返回整个屏幕宽度.当我使用image.size.width时,它返回固定的图像宽度(实际图像宽度).但我的目的是获取UI中显示的运行时图像宽度.
如何从源头找到它.
编辑1
当前景观屏幕中间有标签.标签宽度与imageview相同,但不是当前显示的图像宽度.
最佳答案 请尝试以下代码.它完全符合您对iPhone 6S设备的要求.当设备屏幕方向更改为横向模式时,我正在计算标签框架的x位置和宽度.对于5S和4S等其他设备,您需要根据设备高度宽度比计算x位置和宽度.例如,我使用了一些常量值,如9和18.如果要为不同的设备使用代码,则需要使用比率因子.希望这有帮助!
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var theImageView: UIImageView!
@IBOutlet weak var theLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
theLabel.frame.size.width = (theImageView.image?.size.width)!
NSNotificationCenter.defaultCenter().addObserver(self, selector: "rotated", name: UIDeviceOrientationDidChangeNotification, object: nil)
}
override func viewDidAppear(animated: Bool) {
if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation))
{
if (theImageView.image?.size.height)! > (theImageView.image?.size.width)! {
theLabel.frame.origin.x = (view.frame.size.width - (theImageView.image?.size.height)!)/2
theLabel.frame.size.width = (theImageView.image?.size.height)!
}
else {
theLabel.frame.origin.x = ((theImageView.image?.size.height)!/2) - 9
theLabel.frame.size.width = rint(view.frame.size.width) - (theImageView.image?.size.height)! + 18
}
}
if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation))
{
theLabel.frame.size.width = theImageView.frame.size.width
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
//theImageView.frame.size.width = (theImageView.image?.size.width)!
//theImageView.frame.size.height = (theImageView.image?.size.height)!
}
func rotated()
{
if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation))
{
if (theImageView.image?.size.height)! > (theImageView.image?.size.width)! {
theLabel.frame.origin.x = (view.frame.size.width - (theImageView.image?.size.height)!)/2
theLabel.frame.size.width = (theImageView.image?.size.height)!
}
else {
theLabel.frame.origin.x = ((theImageView.image?.size.height)!/2) - 9
theLabel.frame.size.width = rint(view.frame.size.width) - (theImageView.image?.size.height)! + 18
}
}
if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation))
{
theLabel.frame.size.width = theImageView.frame.size.width
}
}