iOS 8 - 带渐变色文本的UILabel

时间:2014-11-17 22:32:48

标签: ios ios8 core-text

我正在尝试创建一个UILabel文本用渐变着色。渐变是动态的,所以我不能使用静态图像来做到这一点。此外,我发现的每个答案都使用了一些已弃用的CGContext方法(特别是CGContextShowText)。这些方法的弃用说明称"使用核心文本代替"。但是,我并不熟悉Core Text,而且我还没有找到任何方法通过更多搜索来实现。有人知道在iOS 8中这样做的方法吗?谢谢!

1 个答案:

答案 0 :(得分:2)

我将建议一个“解决方法”,即你可以用图像创建一个UIColor,并且可以使用任意数量的库动态创建一个图像。

创建渐变图像的代码大致如下(可能会在某种程度上进行优化):

CGSize size = CGSizeZero; // You should provide this yourself, height is important, width can be limited, for example 3

UIGraphicsBeginImageContextWithOptions(size, NO, 0);

// Assumes fromColor and toColor are UIColors passed into this context
NSArray *colors = @[(id)[fromColor CGColor], (id)[toColor CGColor]];
CGFloat positions[2] = {0.f, 1.f};
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, colors, positions);
CGColorSpaceRelease(colorSpace);

CGContextDrawLinearGradient(ctx, gradient, CGPointMake(0.f, 0.f), CGPointMake(0.f, size.height), kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
CGGradientRelease(gradient);

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

// image contains the linear gradient image you need
UIColor *color = [UIColor colorWithPatternImage:image];
// Simply assign this color to be the textColor of the label