好的,我想通了。基本上,我们可以覆盖drawRectInText 并使用我们自己的图案为填充着色。这样做的好处是我们可以将图像调整到我们的模式框架中。
首先我们创建一个CGPattern 对象并定义一个回调来绘制图案。我们还将标签的大小作为回调中的参数传递。然后我们使用回调中绘制的图案并将其设置为文本的填充颜色:
- (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];
}
回调将图像绘制到上下文中。根据传入回调的帧大小调整图像大小。
void drawImagePattern(void *info, CGContextRef context)
{
UIImage *image = [UIImage imageNamed:@"FontGradientPink.png"];
CGImageRef imageRef = [image CGImage];
CGRect *rect = info;
CGContextDrawImage(context, rect[0], imageRef);
}