为了账号安全,请及时绑定邮箱和手机立即绑定

如何为UILabel的文本(而不是背景)添加渐变?

如何为UILabel的文本(而不是背景)添加渐变?

慕婉清6462132 2019-12-21 13:20:03
嘿,我希望能够对我熟悉的CGGradient的UILabel中的文本进行渐变填充,但是我不知道如何在UILabel的文本中使用它我在Google上找到了它,但我无法使其正常工作http://silverity.livejournal.com/26436.html
查看完整描述

3 回答

?
白板的微信

TA贡献1883条经验 获得超3个赞

Brad Larson和Bach都提供了非常有用的答案。第二个对我有用,但是需要预先显示图像。我想要更具动态性的东西,所以我将两种解决方案结合在一起:


在UIImage上绘制所需的渐变

使用UIImage设置颜色图案

结果有效,在下面的屏幕截图中,您也可以看到一些希腊字符也很好地渲染。(我还在渐变顶部添加了笔触和阴影)


iOS风格化UILabel,大棕狐狸


这是我标签的自定义init方法,以及在UIImage上呈现渐变的方法(我从博客文章中获得的该功能的部分代码,现在找不到它可以引用它):


- (id)initWithFrame:(CGRect)frame text:(NSString *)aText {

    self = [super initWithFrame:frame];

    if (self) {

        self.backgroundColor = [UIColor clearColor];

        self.text = aText;


        self.textColor = [UIColor colorWithPatternImage:[self gradientImage]];


    }

    return self;

}


- (UIImage *)gradientImage

{

    CGSize textSize = [self.text sizeWithFont:self.font];

    CGFloat width = textSize.width;         // max 1024 due to Core Graphics limitations

    CGFloat height = textSize.height;       // max 1024 due to Core Graphics limitations


    // create a new bitmap image context

    UIGraphicsBeginImageContext(CGSizeMake(width, height));


    // get context

    CGContextRef context = UIGraphicsGetCurrentContext();       


    // push context to make it current (need to do this manually because we are not drawing in a UIView)

    UIGraphicsPushContext(context);                             


    //draw gradient    

    CGGradientRef glossGradient;

    CGColorSpaceRef rgbColorspace;

    size_t num_locations = 2;

    CGFloat locations[2] = { 0.0, 1.0 };

    CGFloat components[8] = { 0.0, 1.0, 1.0, 1.0,  // Start color

                            1.0, 1.0, 0.0, 1.0 }; // End color

    rgbColorspace = CGColorSpaceCreateDeviceRGB();

    glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);

    CGPoint topCenter = CGPointMake(0, 0);

    CGPoint bottomCenter = CGPointMake(0, textSize.height);

    CGContextDrawLinearGradient(context, glossGradient, topCenter, bottomCenter, 0);


    CGGradientRelease(glossGradient);

    CGColorSpaceRelease(rgbColorspace); 


    // pop context 

    UIGraphicsPopContext();                             


    // get a UIImage from the image context

    UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();


    // clean up drawing environment

    UIGraphicsEndImageContext();


    return  gradientImage;

}

我将尝试完成该UILabel子类并将其发布。


查看完整回答
反对 回复 2019-12-21
?
智慧大石

TA贡献1946条经验 获得超3个赞

我在寻找解决方案,而DotSlashSlash的答案中隐藏了一个答案!


为了完整起见,答案和最简单的解决方案是:


UIImage *myGradient = [UIImage imageNamed:@"textGradient.png"];

myLabel.textColor   = [UIColor colorWithPatternImage:myGradient];


查看完整回答
反对 回复 2019-12-21
  • 3 回答
  • 0 关注
  • 1005 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信