简体   繁体   English

以编程方式设置框架CGReact x在中间位置,如centerXAnchor NSLayoutConstraint

[英]Set frame CGReact x position in middle like centerXAnchor NSLayoutConstraint programmatically

I am creating a simple app which set image as circle by calculate with frame of image. 我正在创建一个简单的应用程序,通过计算图像frame将图像设置为圆形。

Here is I declare image variable: 这是我声明的图像变量:

lazy var imageUserDetailProfileView: UIImageView = {

    let imageView = UIImageView()


    imageView.contentMode = .scaleAspectFill
    imageView.layer.borderWidth = 1
    imageView.image = UIImage(named: "profile-icon")
    imageView.layer.borderColor = UIColor(red:0.00, green:0.50, blue:0.00, alpha:1.0).cgColor
    imageView.clipsToBounds = true

    return imageView


}()

Here is i made that frame width and height of image became circle 这是我使图像的框架宽度和高度变成圆形的

imageUserDetailProfileView.frame = CGRect(x: view.frame.midX, y: 20,width: 100, height: 100)
imageUserDetailProfileView.layer.cornerRadius = imageUserDetailProfileView.frame.height/2

Now i want image should stay in middle of screen like using NSLayoutConstraint which has method centerXAnchor . 现在我希望图像应该像使用NSLayoutConstraint那样保留在屏幕中间,该方法具有centerXAnchor方法。

How to solve this problem? 如何解决这个问题呢?

let midX = view.frame.size.width / 2
let midY = view.frame.size.height / 2

Try This Code. 尝试此代码。 Custom Method For Image Set In Center Of Any View. 在任何视图的中心设置图像的自定义方法。 Just Call Method And Pass Image & View. 只需调用方法并传递图像和视图即可。 Customize according to Use. 根据用途定制。 Swift 4 斯威夫特4

  func setImageInCenterOfView(image:UIImage,view:UIView) {

    let imageWidth:CGFloat = 100
    let myImageView = UIImageView.init(frame: CGRect.init(x: (view.frame.size.width/2)-imageWidth/2, y: (view.frame.size.height/2)-imageWidth/2, width: imageWidth, height: imageWidth))
    myImageView.clipsToBounds = true
    myImageView.layer.cornerRadius = myImageView.frame.size.height/2
    myImageView.image = image
    view.addSubview(myImageView)
    view.layoutIfNeeded()
  }

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

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