在Cocoa中使用渐变填充绘制文本

3

我有一个项目需要在NSView的自定义子类中绘制带渐变填充的文本,就像下面的示例一样。

alt text

我想知道如何实现这个功能,因为我对Cocoa绘图还比较陌生。

1个回答

3
尝试使用从文本创建alpha掩模,然后使用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);
}

这将视图边界用作渐变边界;如果您想更准确,需要获取文本高度(关于此信息在此)。

1
谢谢!我还在苹果的示例代码(SpeedometerView)中找到了一个类别,可以将字符串转换为贝塞尔路径,其余的事情就是简单地转换路径并用渐变填充它。 - koo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接