ios - Swift 中仅平滑顶部角度和 ImageView

标签 ios swift rounded-corners cornerradius

我试图只圆化 View 和 ImageView 的顶部角(左上和右上)。使用下面的代码,我只能将左上角舍入(尽管也指定了 TopRight)。也许他没有看到 Storyboard上的限制。

我该如何解决?

谢谢。

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
}

但是没有成功。

最佳答案

我已经尝试过您发布的代码。无论出于何种原因,当我输入约束并重新创建 View 层次结构时,自动布局引擎在执行第二遍后不会调用 viewDidLayoutSubviews 。我可以强制它,但从 viewWillAppear 调用 self.view.layoutIfNeeded() 。例如:

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

两个角都是圆角的。

我想说,避免这种自动布局故障的更好、更优雅的解决方案是仅设置 ImageView 容器的角半径,因为看起来您无论如何都在做。例如:

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

您还可以通过 viewDidLoad 执行此操作,因为它不依赖于设置的任何 View 框架。

enter image description here

关于ios - Swift 中仅平滑顶部角度和 ImageView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37713559/

相关文章:

ios - 中间透明的UIView

iphone - 向核心数据实体添加属性

ios - 允许用户仅在 Swift 中输入下一个可用的文本字段

android - 如何在Firemonkey中创建圆角T矩形?

android - google-api-v2 中的 Mapview 在 android 中带有圆角

javascript - 使用 React-Native 在 ScrollView 中的特定位置进行缩放

ios - 为什么我的 UIImageView 替换了第二个?

ios - 使用 UIDiffableDataSource TableView 删除项目时,不会调用 NFetchedResultsController 委托(delegate)方法 didChangeContentWith

swift - "Cannot convert value of type ' () ' to UIImage": Swift

jquery - 计算内部元素的圆 Angular 边框大小以匹配外部元素