在Swift中仅平滑顶角和imageview

时间:2016-06-08 21:50:17

标签: ios swift rounded-corners cornerradius

我试图只围绕视图和imageview的顶部顶角(TopLeft和TopRight)。使用下面的代码,我只能向左上角(尽管还指定了TopRight)。也许他没有看到故事板上的约束。

我该如何解决?

谢谢。

let rectShape = CAShapeLayer()
        rectShape.bounds = self.CopertinaImage1.frame
        rectShape.position = self.CopertinaImage1.center
        rectShape.path = UIBezierPath(roundedRect: self.CopertinaImage1.bounds, byRoundingCorners: [.TopRight, .TopLeft], cornerRadii: CGSize(width: 10, height: 10)).CGPath

        self.CopertinaImage1.layer.backgroundColor = UIColor.greenColor().CGColor
        self.CopertinaImage1.layer.mask = rectShape

右角总是一样的: enter image description here 修改

我已尝试将以下代码放入viewDidLayoutSubviews

override func viewDidLayoutSubviews() { 
    super.viewDidLayoutSubviews() 
    let rectShape = CAShapeLayer() 
    rectShape.bounds = self.CopertinaImage1.frame 
    rectShape.position = self.CopertinaImage1.center 
    rectShape.path = UIBezierPath(roundedRect: self.CopertinaImage1.bounds, byRoundingCorners: [.TopRight, .TopLeft], cornerRadii: CGSize(width: 10, height: 10)).CGPath 
    self.CopertinaImage1.layer.backgroundColor = UIColor.greenColor().CGColor 
    self.CopertinaImage1.layer.mask = rectShape
}

但它没有用。

2 个答案:

答案 0 :(得分:0)

我刚刚在操场上试过你的代码。为我工作得很好。也许我误解了这个问题。

enter image description here

答案 1 :(得分:0)

我已经尝试了你发布的代码。无论出于何种原因,当我输入约束并重新创建视图层次结构时,自动布局引擎在第二次传递后不会调用viewDidLayoutSubviews。我可以强迫它,但是从self.view.layoutIfNeeded()拨打viewWillAppear。例如:

override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        let rectShape = CAShapeLayer()
        rectShape.frame = self.imageView.bounds
        rectShape.path = UIBezierPath(roundedRect: self.imageView.bounds, byRoundingCorners: [.TopRight, .TopLeft], cornerRadii: CGSize(width: 10, height: 10)).CGPath
        self.imageView.layer.backgroundColor = UIColor.greenColor().CGColor
        self.imageView.layer.mask = rectShape
}

override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.view.layoutIfNeeded()
    }

结果:

enter image description here

两个角落圆润。

我想说一个更好,更优雅的解决方案,避免这种自动布局故障只是设置图像视图容器的角半径,因为它似乎是你正在做的事情。例如:

override func viewDidLoad() {
        super.viewDidLoad()
        self.imageView.clipsToBounds = true
        self.imageContainerView.layer.cornerRadius = 10.0
        self.imageContainerView.layer.masksToBounds = true
    }

您也可以从viewDidLoad执行此操作,因为它不依赖于您设置的任何视图框架。

enter image description here