Circular UIImageView在某些设备上是正方形的
问题描述:
我有一个UIView
,其中有一个UIImageView
。Circular UIImageView在某些设备上是正方形的
我设置UIImageView
是圆形的,并添加边框像这样:
self.profilePicImageView.layer.cornerRadius = self.profilePicImageView.frame.size.height/2
self.profilePicImageView.layer.masksToBounds = true
self.profilePicImageView.layer.borderColor = UIColor.white.cgColor
self.profilePicImageView.layer.borderWidth = 3
它被称为后我初始化我viewController
的观点之前,我将它添加为子视图(函数调用setupUI()
)。
它在大多数设备上都能很好地工作,但在大屏幕设备(iPhone 6/6s/7 Plus和iPhone X)上,我获得了正确的边框,但图像本身不是圆形的。
请看例子:
普通的iPhone:
大型的iPhone(iPhone 6/6S/7 Plus和iPhone X):
任何想法可能是什么问题,我该如何解决它?
谢谢!
答
这只是因为你的内容模式 尝试不同的contentMode像
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleBottomMargin, .flexibleRightMargin, .flexibleLeftMargin, .flexibleTopMargin]
imageView.contentMode = .scaleAspectFit // OR .scaleAspectFill
imageView.clipsToBounds = true
答
创建自定义的ImageView类,如:
@IBDesignable class RoundedImageView:UIImageView {
@IBInspectable var borderColor:UIColor = UIColor.white {
willSet {
layer.borderColor = newValue.cgColor
}
}
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = frame.height/2
layer.masksToBounds = true
layer.borderWidth = 1
layer.borderColor = borderColor.cgColor
}
}
并设置ImageView的自定义类 “RoundedImageView”。
@ FS.06 I'hd也面临这样的问题,所以添加下面一行代码 self.profilePicImageView.contentMode = .scaleAspectFill self.profilePicImageView.clipsToBounds =真 –
@ FS.O6请尝试我的编辑答案,这是为我工作 – SPatel