2010-10-27 39 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