【发布时间】:2010-11-04 15:32:31
【问题描述】:
我遇到了 NSString 方法 drawAtPoint 和 kCGTextFillClip 的问题。我需要创建一个带有渐变而不是简单颜色的 UILabel,所以我对它进行了子类化并覆盖了 drawRect 方法。我设法通过使用函数 CGContextShowTextAtPoint 得到我想要的,但它不能正确处理 UTF-8,这对我来说很重要。
我知道这是一个常见的问题,所以在搜索了一下之后,我发现我可以使用 drawAtPoint 来解决这个编码问题。实际上,文本现在可以正确显示。问题是我不知道如何让 kCGTextFillClip 工作了。
看看result。
如您所见,它似乎可以很好地剪辑到第一个字母,但之后就不行了。您对如何解决此问题有任何想法吗?
这是我正在使用的代码:
- (void)drawRect:(CGRect)rect {
CGContextRef theContext = UIGraphicsGetCurrentContext();
CGRect viewBounds = self.bounds;
CGContextSaveGState(theContext);
CGContextTranslateCTM(theContext, 0.0, viewBounds.size.height/2 + 1);
CGContextSetTextDrawingMode(theContext, kCGTextFillClip);
[self.text drawAtPoint:CGPointMake(0, 0) withFont:[UIFont fontWithName:@"Helvetica-Bold" size:11.5]];
// Creation of the gradient
CGFloat locations[2] = { 0.0f, 1.0f };
CGFloat components[8] = {
190.0/255, 190.0/255, 190.0/255, 1.0, // Start color
113.0/255, 113.0/255, 113.0/255, 1.0 // End color
};
CGColorSpaceRef rgbColorspace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, 2);
CGPoint topCenter = CGPointMake(CGRectGetMidX(viewBounds), 0.0f);
CGPoint midCenter = CGPointMake(CGRectGetMidX(viewBounds), CGRectGetMidY(viewBounds));
CGContextDrawLinearGradient(theContext, gradient, topCenter, midCenter, 0);
谢谢!
【问题讨论】:
标签: ios uilabel gradient quartz-graphics