ios - UILabel 添加渐变图层

标签 ios uilabel cagradientlayer

<分区>

要向 UILabel 添加背景渐变,我使用以下代码。

在使用渐变之前,UILabel 是这样的。

WithOut Gradient

现在,要添加渐变,我使用以下代码。

   CAGradientLayer *gradLayer=[CAGradientLayer layer];
    gradLayer.frame=self.myView.layer.bounds;
    [gradLayer setColors:[NSArray arrayWithObjects:(id)([UIColor redColor].CGColor), (id)([UIColor cyanColor].CGColor),nil]];
    gradLayer.endPoint=CGPointMake(1.0, 0.0);

    [self.myView.layer addSublayer:gradLayer];

UILabel 如下所示,但没有文本。

With Gradient

我也尝试在 UILabel 层的底部添加层,但没有成功。

[self.myView.layer insertSublayer:gradLayer atIndex:0];

最佳答案

您可能需要将标签设置在不同的 UIView 之上:

 UIView *labelBackground = [[UIView alloc] initWithFrame:self.label.frame];
 self.label.backgroundColor = [UIColor clearColor];
 self.label.frame = self.label.bounds;

 CAGradientLayer *gradLayer=[CAGradientLayer layer];
 gradLayer.frame = labelBackground.layer.bounds;
 [gradLayer setColors:[NSArray arrayWithObjects:(id)([UIColor redColor].CGColor), (id)([UIColor cyanColor].CGColor),nil]];
 gradLayer.endPoint=CGPointMake(1.0, 0.0);

 [labelBackground.layer addSublayer:gradLayer];

 [labelBackground addSubview:self.label];

 [self.view addSubview:labelBackground];

关于ios - UILabel 添加渐变图层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16496359/

相关文章:

ios - Xcode/Swift 为所有同名按钮添加渐变层

ios - 如何使用 UILabel 创建发光效果?

ios - 从点击获取 UILabel 中的字符索引

ios - 我们如何将一个 UIView 设置为另一个 UIView 的掩码

iphone - CAGradientLayer,无法很好地调整大小,旋转时撕裂

objective-c - UIScrollView 不会调整高度以适应 subview

ios - Swift - 在 UIImageView/UIScrollView 之上的 UIView

ios - 栏按钮在运行时未显示在导航栏上

ios - 无法将 UITableView 限制到安全区域

ios - 如何在 UIView 上绘制一个 NSStrings 数组,它们之间没有任何前导空间并占据整个矩形?