【问题标题】:All four corner of a view having different radius具有不同半径的视图的所有四个角
【发布时间】:2018-01-29 21:55:32
【问题描述】:

如何设计一个所有 4 个角都具有不同角半径的 UIView。所以,UIView 的右上角半径为 20,左上角半径为 30,左下角半径为 10,右下角半径为 20

我想向图中显示的 Viw Container 添加不同的cornerRadius。 使用 UIBEZIER 方法会切断分享评论和喜欢的部分。 viw 容器被固定到单元格

【问题讨论】:

标签: ios swift uiview


【解决方案1】:

您可以使用此 UIView 扩展。它将根据您的半径值创建和应用遮罩层。

extension UIView {
func applyRadiusMaskFor(topLeft: CGFloat = 0, bottomLeft: CGFloat = 0, bottomRight: CGFloat = 0, topRight: CGFloat = 0) {

    let path = UIBezierPath()
    path.move(to: CGPoint(x: bounds.width - topRight, y: 0))
    path.addLine(to: CGPoint(x: topLeft, y: 0))
    path.addQuadCurve(to: CGPoint(x: 0, y: topLeft), controlPoint: .zero)
    path.addLine(to: CGPoint(x: 0, y: bounds.height - bottomLeft))
    path.addQuadCurve(to: CGPoint(x: bottomLeft, y: bounds.height), controlPoint: CGPoint(x: 0, y: bounds.height))
    path.addLine(to: CGPoint(x: bounds.width - bottomRight, y: bounds.height))
    path.addQuadCurve(to: CGPoint(x: bounds.width, y: bounds.height - bottomRight), controlPoint: CGPoint(x: bounds.width, y: bounds.height))
    path.addLine(to: CGPoint(x: bounds.width, y: topRight))
    path.addQuadCurve(to: CGPoint(x: bounds.width - topRight, y: 0), controlPoint: CGPoint(x: bounds.width, y: 0))

    let shape = CAShapeLayer()
    shape.path = path.cgPath
    layer.mask = shape
}
}

示例用法:

let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.backgroundColor = .red
view.applyRadiusMaskFor(topLeft: 80, bottomLeft: 40, bottomRight: 30, topRight: 60)

结果:Radius applied image

【讨论】:

  • 不要忘记在每次视图调整大小时调用这个函数。
  • 我在我的视图中使用了这个,但问题是切断了我的视图的底部,在左上角和右上角都可以正常工作。 @aleksmutlu
  • 您是否在应用蒙版后调整视图大小?就像@Samah 说的那样,您需要为每次尺寸变化重新涂抹面膜。
  • 如果您使用自动布局,请尝试在应用遮罩之前调用 layoutIfNeeded()。 theViewYouApplyMask.layoutIfNeeded() theViewYouApplyMask.applyRadiusMaskFor(... @NikeshHyanju
  • 没有尝试过但失败了!我似乎做错了,我使用了其他不同的方法,但无论我做什么,它总是切断底部
猜你喜欢
  • 2022-10-17
  • 2023-04-03
  • 1970-01-01
  • 2019-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多