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

嘿,我希望能够对我熟悉的CGGradient的UILabel中的文本进行渐变填充,但是我不知道如何在UILabel的文本中使用它


我在Google上找到了它,但我无法使其正常工作


http://silverity.livejournal.com/26436.html


慕婉清6462132
浏览 1015回答 3
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子类并将其发布。

智慧大石

我在寻找解决方案,而DotSlashSlash的答案中隐藏了一个答案!为了完整起见,答案和最简单的解决方案是:UIImage *myGradient = [UIImage imageNamed:@"textGradient.png"];myLabel.textColor   = [UIColor colorWithPatternImage:myGradient];
打开App,查看更多内容
随时随地看视频慕课网APP