问题描述
我想为我的文本的填充颜色创建一个渐变.目前我正在通过将 UILabel 文本的颜色设置为
I want to create a gradient for the fill color of my text. Currently I am doing it by setting the color of a UILabel's text as
UIImage *image = [UIImage imageNamed:@"GradientFillImage.png"];
myLabel.textColor = [UIColor colorWithPatternImage:image];
其中 GradientFillImage.png
是一个简单的图像文件,上面绘有线性渐变.
Where GradientFillImage.png
is a simple image file with a linear gradient painted on it.
在我想调整字体大小之前,这可以正常工作.由于图像文件具有恒定尺寸并且在我调整字体大小时不会调整大小,因此字体的渐变填充会变得混乱.如何创建自定义大小的图案图像并将其用作文本的填充图案?
This works fine until I want to resize the font. Since the image file is of constant dimensions and does not resize when I resize the font, the gradient fill for the font gets messed up. How do I create a custom size pattern image and apply it as a fill pattern for text?
推荐答案
好的,我想通了.基本上,我们可以覆盖 drawRectInText
并使用我们自己的模式来为填充着色.这样做的好处是我们可以将图像调整到我们的模式框架中.
Ok, I figured it out. Basically, we can override drawRectInText
and use our own pattern to color the fill. The advantage of doing this is that we can resize the image into our pattern frame.
首先我们创建一个CGPattern 对象并定义一个回调来绘制图案.我们还将标签的大小作为回调中的参数传递.然后我们使用回调中绘制的图案并将其设置为文本的填充颜色:
First we create a CGPattern object and define a callback to draw the pattern. We also pass the size of the label as a parameter in the callback. We then use the pattern that is drawn in the callback and set it as the fill color of the text:
- (void)drawTextInRect:(CGRect)rect
{
//set gradient as a pattern fill
CGRect info[1] = {rect};
static const CGPatternCallbacks callbacks = {0, &drawImagePattern, NULL};
CGAffineTransform transform = CGAffineTransformMakeScale(1.0, -1.0);
CGPatternRef pattern = CGPatternCreate((void *) info, rect, transform, 10.0, rect.size.height, kCGPatternTilingConstantSpacing, true, &callbacks);
CGColorSpaceRef patternSpace = CGColorSpaceCreatePattern(NULL);
CGFloat alpha = 1.0;
CGColorRef patternColorRef = CGColorCreateWithPattern(patternSpace, pattern, &alpha);
CGColorSpaceRelease(patternSpace);
CGPatternRelease(pattern);
self.textColor = [UIColor colorWithCGColor:patternColorRef];
self.shadowOffset = CGSizeZero;
[super drawTextInRect:rect];
}
回调将图像绘制到上下文中.根据传入回调的帧大小调整图像大小.
The callback draws the image into the context. The image is resized as per the frame size that is passed into the callback.
void drawImagePattern(void *info, CGContextRef context)
{
UIImage *image = [UIImage imageNamed:@"FontGradientPink.png"];
CGImageRef imageRef = [image CGImage];
CGRect *rect = info;
CGContextDrawImage(context, rect[0], imageRef);
}
这篇关于使用 [UIColor colorWithPatternImage:] 为文本创建渐变填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!