简体   繁体   English

如何使用CGRect以编程方式在父视图中垂直居中UIImage?

[英]How to center vertically UIImage inside parent view programmatically using CGRect?

I tried to do this one but, the place of the Image changes when I try to run on a different iPhone model in Simulator.我尝试这样做,但是当我尝试在模拟器中的不同 iPhone 型号上运行时,图像的位置发生了变化。 I need to do this exactly with CGRect.我需要用 CGRect 完全做到这一点。 Thanks in Advance!提前致谢!

    func configure() {
        //MARK: Logo Image
        view.addSubview(logo)
        logo.image = UIImage(named: "cafelogo")
        logo.layer.cornerRadius = 25
        logo.frame = CGRect(x: 100, y: 200, width: 150, height: 150)

You should be using auto-layout constraints -- but first, to show you how to do this with explicit rect / framing:您应该使用自动布局约束——但首先,向您展示如何使用显式矩形/框架来执行此操作:

func configure() {
    //MARK: Logo Image
    view.addSubview(logo)
    logo.image = UIImage(named: "cafelogo")
    logo.layer.cornerRadius = 25
    logo.frame = CGRect(x: 0, y: 0, width: 150, height: 150)
    // center it in the view
    logo.center = view.center
}

but... you have to call this from viewDidLayoutSubviews() .但是...您必须从viewDidLayoutSubviews()调用它。 Otherwise, view 's frame has not yet been laid-out:否则, view的框架还没有被布局:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    configure()
}

Note that if the frame of view changes - such as on device rotation - your logo image view will no longer be centered.请注意,如果view框架发生变化 - 例如设备旋转 - 您的徽标图像视图将不再居中。 You could add some new code to re-center it, but it is much easier to let auto-layout do all the work.可以添加一些新代码来重新居中,但让自动布局完成所有工作要容易得多。

You can use this code in viewDidLoad() :您可以在viewDidLoad()中使用此代码:

    logo.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(logo)
    logo.image = UIImage(named: "cafelogo")
    logo.layer.cornerRadius = 25
    NSLayoutConstraint.activate([
        logo.widthAnchor.constraint(equalToConstant: 150.0),
        logo.heightAnchor.constraint(equalToConstant: 150.0),
        logo.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        logo.centerYAnchor.constraint(equalTo: view.centerYAnchor),
    ])

Now your logo image view is 150x150 and will always remain centered in view .现在您的徽标图像视图是 150x150 并且将始终保持在view中心。

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

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