Swift 3: 图片不适合圆形边框
Swift 3: image does not fit to circle border
我需要在导航栏标题的圆形边框上放置一张图片。下面的代码应该放置一个圆形边框并设置一个约束。问题是圆圈比我上传的图片所示的图片大。我能做什么?谢谢。
let imageView = UIImageView(image: profileImageResized)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
imageView.layer.cornerRadius = imageView.frame.size.width/2
imageView.layer.borderWidth = 1
imageView.layer.borderColor = UIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 100.0).cgColor
imageView.clipsToBounds = true
view.addSubview(imageView)
let verticalSpace = NSLayoutConstraint(item: imageView,
attribute: .top,
relatedBy: .equal,
toItem: self.topLayoutGuide,
attribute: .bottom,
multiplier: 1, constant: 0)
view.addConstraints([verticalSpace])
您应该将 imageView
的 contentMode 设置为 .scaleAspectFill
。这样,图像将填满它的框架,同时也尊重它的外观。
imageView.contentMode = .scaleAspectFill
我需要在导航栏标题的圆形边框上放置一张图片。下面的代码应该放置一个圆形边框并设置一个约束。问题是圆圈比我上传的图片所示的图片大。我能做什么?谢谢。
let imageView = UIImageView(image: profileImageResized)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
imageView.layer.cornerRadius = imageView.frame.size.width/2
imageView.layer.borderWidth = 1
imageView.layer.borderColor = UIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 100.0).cgColor
imageView.clipsToBounds = true
view.addSubview(imageView)
let verticalSpace = NSLayoutConstraint(item: imageView,
attribute: .top,
relatedBy: .equal,
toItem: self.topLayoutGuide,
attribute: .bottom,
multiplier: 1, constant: 0)
view.addConstraints([verticalSpace])
您应该将 imageView
的 contentMode 设置为 .scaleAspectFill
。这样,图像将填满它的框架,同时也尊重它的外观。
imageView.contentMode = .scaleAspectFill