【问题标题】:How do I round only the top two corners of a UILabel?如何仅舍入 UILabel 的前两个角?
【发布时间】:2012-01-27 14:00:11
【问题描述】:

我知道在 iOS 3.0+ 中我可以使用

 label.layer.cornerRadius = xxx;

圆 UILabel 的所有四个角(作为 UIView 子类),但我只想圆化标签的顶部两个角并保持底部角成直角。

有什么方法可以用 UILabel 做到这一点?其他解决方案假定使用自定义 UIView,而不是 UILabel。

【问题讨论】:

    标签: iphone objective-c ios uilabel


    【解决方案1】:

    我想我会发布包含 BezierPath 的完整代码。

    CGRect bounds = label.bounds;
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:bounds
                                                                       byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight)
                                                                             cornerRadii:CGSizeMake(5.0, 5.0)];
    
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = bounds;
    maskLayer.path = maskPath.CGPath;
    
    label.layer.mask = maskLayer;
    

    对于 Swift 4.0:

    let bounds: CGRect = label.bounds
    let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: ([.topLeft, .topRight]), cornerRadii: CGSize(width: 5.0, height: 5.0))
    let maskLayer = CAShapeLayer()
    maskLayer.frame = bounds
    maskLayer.path = maskPath.cgPath
    label.layer.mask = maskLayer
    

    【讨论】:

      【解决方案2】:

      您可以使用 CALayers 和遮罩来做到这一点

      CAShapeLayer *maskLayer = [CAShapeLayer layer];
      maskLayer.path = maskPath.CGPath;
      label.layer.mask = maskLayer;
      

      其中 maskPath 是使用 bezierPathWithRoundedRect:byRoundingCorners:cornerRadii 设置的 UIBezierPath

      【讨论】:

      • 我觉得应该是 label.layer.mask = maskLayer
      • 接受了这个答案,因为我不想在这里使用额外的视图。我正在使用两个覆盖层,底层都是圆形的,顶层只有顶部两个角是圆形的。为了达到这个效果icons.iconarchive.com/icons/walrick/openphone/256/…
      【解决方案3】:

      我已经检查了 UIView 和 UILabel 及其层的类参考,但找不到任何方法来使用 iOS 提供的方法。

      您可以做一件事,创建一个UIView 并为其应用圆角。现在将UILabel 作为子视图添加到此 UIView 并以这样的方式定位它,以便底部的 2 个圆角被标签覆盖。这样你就可以得到你需要的效果...

      【讨论】:

      • 并确保 UIView 和 UILabel 具有相同的颜色。
      猜你喜欢
      • 2018-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-11
      • 1970-01-01
      • 2022-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多