2010-10-27 30 views
2

我有一个项目,需要在渐变填充NSView的自定义子类的视图中绘制文本,如下面的示例所示。绘制带有渐变的文字填充可可

alt text

我不知道我怎么能做到这一点,因为我是很新,可可图。

回答

2

尝试creating an alpha mask from the text然后使用NSGradient绘制它。以下是一个基于链接代码的简单示例:

- (void)drawRect:(NSRect)rect 
{ 
    // Create a grayscale context for the mask 
    CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceGray(); 
    CGContextRef maskContext = 
    CGBitmapContextCreate(
     NULL, 
     self.bounds.size.width, 
     self.bounds.size.height, 
     8, 
     self.bounds.size.width, 
     colorspace, 
     0); 
    CGColorSpaceRelease(colorspace); 

    // Switch to the context for drawing 
    NSGraphicsContext *maskGraphicsContext = 
     [NSGraphicsContext 
      graphicsContextWithGraphicsPort:maskContext 
      flipped:NO]; 
    [NSGraphicsContext saveGraphicsState]; 
    [NSGraphicsContext setCurrentContext:maskGraphicsContext]; 

    // Draw the text right-way-up (non-flipped context) 
    [text 
     drawInRect:rect 
     withAttributes: 
      [NSDictionary dictionaryWithObjectsAndKeys: 
       [NSFont fontWithName:@"HelveticaNeue-Bold" size:124], NSFontAttributeName, 
       [NSColor whiteColor], NSForegroundColorAttributeName, 
      nil]]; 

    // Switch back to the window's context 
    [NSGraphicsContext restoreGraphicsState]; 

    // Create an image mask from what we've drawn so far 
    CGImageRef alphaMask = CGBitmapContextCreateImage(maskContext); 

    // Draw a white background in the window 
    CGContextRef windowContext = [[NSGraphicsContext currentContext] graphicsPort]; 
    [[NSColor whiteColor] setFill]; 
    CGContextFillRect(windowContext, rect); 

    // Draw the gradient, clipped by the mask 
    CGContextSaveGState(windowContext); 
    CGContextClipToMask(windowContext, NSRectToCGRect(self.bounds), alphaMask); 

    NSGradient *gradient = [[NSGradient alloc] initWithStartingColor:[NSColor blackColor] endingColor:[NSColor grayColor]]; 
    [gradient drawInRect:rect angle:-90]; 
    [gradient release]; 

    CGContextRestoreGState(windowContext); 
    CGImageRelease(alphaMask); 
} 

这使用视图边界作为渐变边界;如果你想更准确,你需要得到文本高度(有关该信息here)。

+1

谢谢!我还从Apple的示例代码(SpeedometerView)中找到了一个类别,用于将字符串转换为贝塞尔路径的NSString,其余部分仅改变路径并用渐变填充。 – koo 2010-12-06 03:25:24