如何仅为UILabel的左上角设置cornerRadius?

5
import UIKit

class ViewController: UIViewController {

@IBOutlet weak var myText: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
 }
}

5个回答

11

iOS 11 开始,请使用 Masked Corners 属性。

现在有一个用于图层的 maskedCorners 属性。这是一个 CACornerMask,每个角落都有四个可能的值:

  • layerMaxXMaxYCorner - 右下角
  • layerMaxXMinYCorner - 右上角
  • layerMinXMaxYCorner - 左下角
  • layerMinXMinYCorner - 左上角

创建一个扩展以更好地使用:

extension UIView {

   func roundCorners(corners:CACornerMask, radius: CGFloat) {
      self.layer.cornerRadius = radius
      self.layer.maskedCorners = corners
   }
}

例子:

class CustomCell: UICollectionViewCell {

   override func layoutSubviews() {
      //Round left and righ top corners
      yourView.roundCorners(corners: [.layerMinXMinYCorner, .layerMaxXMinYCorner], radius: radius)
   }    
}

10

尝试这段代码

在 Xcode 8 和 Swift 3 中测试通过

extension UIView {
    func roundCorners(corners:UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask
    }
}

并且像这样使用

lable.roundCorners(corners: [.topLeft], radius: 10)

感谢您节省了我的时间……它的效果很棒。 易于操作,非常简单!! - Let.Simoo

4
let path =  UIBezierPath(roundedRect: self.bounds, byRoundingCorners: .topLeft, cornerRadii: CGSize(width: 10.0, height: 10.0))
let maskLayer = CAShapeLayer()
maskLayer.path = path.cgPath
myText.layer.mask = maskLayer

您可以在您的UILabel类中使用。
override func draw(_ rect: CGRect) {
    let path =  UIBezierPath(roundedRect: self.bounds, byRoundingCorners: .topLeft, cornerRadii: CGSize(width: 10.0, height: 10.0))
    let maskLayer = CAShapeLayer()
    maskLayer.path = path.cgPath
    self.layer.mask = maskLayer
}

2

您需要添加以下行来设置圆角:

let radius = 15.0
 let layer = CAShapeLayer()
 let  shadowPath = UIBezierPath(roundedRect: myText.frame, byRoundingCorners: ([.topLeft]), cornerRadii: CGSize(width: radius, height: radius ))
layer.path = shadowPath.cgPath
myText.layer.mask = layer

2

试一下,这对我很有效。

 var textPath = UIBezierPath(roundedRect: myText.bounds, byRoundingCorners: 
                (.topLeft), cornerRadii: CGSize(width: 10.0, height: 10.0))
 var textLayer = CAShapeLayer()
 textLayer.frame = myText.bounds
 textLayer.path = textPath.cgPath
 myText.layer.mask = maskLayer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接