在Swift中使ui图像完美循环
我试图通过Swift中的代码将表格视图单元格中的UIImage视图变成一个完美的圆圈。 首先,我把在Swift中使ui图像完美循环,swift,xcode,programmatically,Swift,Xcode,Programmatically,我试图通过Swift中的代码将表格视图单元格中的UIImage视图变成一个完美的圆圈。 首先,我把img.layer.cornerRadius=35放在我的代码中,它使我的图像几乎像一个圆。然后,我没有向拐角半径传递一个数字,而是尝试按代码编写该部分,类似于img.layer.cornerRadius=img.frame.height/2。但是,此代码使UIImage成为正方形(不应用角半径)。我不知道为什么会这样。有人能解释一下为什么会发生这种情况以及如何解决吗 class Reposit
img.layer.cornerRadius=35
放在我的代码中,它使我的图像几乎像一个圆。然后,我没有向拐角半径传递一个数字,而是尝试按代码编写该部分,类似于img.layer.cornerRadius=img.frame.height/2
。但是,此代码使UIImage成为正方形(不应用角半径)。我不知道为什么会这样。有人能解释一下为什么会发生这种情况以及如何解决吗
class RepositoryCell:UITableViewCell{
让userImageView:UIImageView={
设img=UIImageView()
img.contentMode=.scaleSpectFit
img.layer.cornerRadius=img.frame.height/2
//img.layer.cornerRadius=35因为让img=UIImageView()
->frame==0
您可以这样做:
class RepositoryCell: UITableViewCell {
...
override func layoutSubviews() {
super.layoutSubviews()
userImageView.layer.cornerRadius = img.frame.height / 2
}
...
}
因为让img=UIImageView()
您可以这样做:
class RepositoryCell: UITableViewCell {
...
override func layoutSubviews() {
super.layoutSubviews()
userImageView.layer.cornerRadius = img.frame.height / 2
}
...
}
如果使用RxSwift,只需调用img.cornerHalf()
它使用关键路径
let userImageView: UIImageView = {
let img = UIImageView()
// ...
img.cornerHalf()
// ...
return img
}()
使用下面的辅助代码
import RxSwift
import RxCocoa
extension UIView{
func cornerHalf(){
clipsToBounds = true
rx.observe(CGRect.self, #keyPath(UIView.bounds))
.subscribe(onNext: { _ in
// _ : CGRect? in
self.layer.cornerRadius = self.bounds.height * 0.5
}).disposed(by: rx.disposeBag)
}
}
如果使用RxSwift,只需调用img.cornerHalf()
它使用关键路径
let userImageView: UIImageView = {
let img = UIImageView()
// ...
img.cornerHalf()
// ...
return img
}()
使用下面的辅助代码
import RxSwift
import RxCocoa
extension UIView{
func cornerHalf(){
clipsToBounds = true
rx.observe(CGRect.self, #keyPath(UIView.bounds))
.subscribe(onNext: { _ in
// _ : CGRect? in
self.layer.cornerRadius = self.bounds.height * 0.5
}).disposed(by: rx.disposeBag)
}
}
cornerRadius是在图像视图尚未渲染时设置的(使用惰性声明),此时其帧仍然为零。因此,让我们在init中为图像视图设置帧,或者在awakeFromNib()/layoutSubviews()中设置cornerRadius。无论如何,角半径是制作圆形图像的糟糕方法。相反,将遮罩设置为圆形。当图像视图尚未渲染时(使用惰性声明),会设置角半径,此时其帧仍然为零。因此,让我们在init中为图像视图设置一个帧,或者在awakeFromNib()/layoutSubviews()中设置角半径.无论如何,角半径是制作圆形图像的一种糟糕方法。相反,请将其遮罩为圆形。