ios - 圆形 ImageView

标签 ios swift uiimageview nslayoutconstraint

我正在尝试为个人资料图片圈出 ImageView 。 在我限制 UiScreen 宽度之前它工作正常。

代码如下

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var imageView: UIImageView!

@IBOutlet weak var proPicH: NSLayoutConstraint! //Profile Picture Height
@IBOutlet weak var proPicW: NSLayoutConstraint! // Profile Picture Width

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    circleImage()
}

func circleImage() {
    let screenSize = UIScreen.mainScreen().bounds
    let screenWidth = screenSize.width
    let width = screenWidth / 2
    print("ScreenWidth: \(screenWidth)")
    proPicW.constant = width
    proPicH.constant = width

    print("H:\(proPicH.constant)")
    print("W:\(proPicW.constant)") //Here the height and width comes to my expectations

    imageView.layer.cornerRadius = imageView.bounds.width / 2
    imageView.clipsToBounds = true

    print("Height: \(imageView.bounds.height)") // Here the height and width becomes more
}
}

Here is how image comes, I want it to be round

请帮我把图片弄圆

最佳答案

在您设置 ImageView 角半径的时间点,其边界尚未更新以匹配约束。改变这一行

imageView.layer.cornerRadius = imageView.bounds.width / 2

imageView.layer.cornerRadius = width / 2

因此用于设置约束的相同值也用于角半径。

请注意,如果您更新其他代码段中的约束,您还需要更新拐角半径以匹配。

关于ios - 圆形 ImageView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35547149/

相关文章:

ios - Swift 中的自定义相机和裁剪图像

iOS:如何仅在用户拖动滚动条时才允许滚动?

iphone - ios 旋转后图像边框变得模糊

ios - Facebook 与 IOS 集成

ios - iPhone GPS导航不会退出

ios wants FullScreenLayout 状态栏可见

ios - 由于内存压力而终止

ios - CALayers : A) Can I draw directly on them and B) How to make a width adjustment on a superlayer affect a sublayer

ios - 在另一个 View Controller 中添加一个 View Controller 作为 subview

ios - UIImageView 保持宽高比,但适合宽度