【问题标题】:Drawing text with gradient fill in Cocoa在 Cocoa 中使用渐变填充绘制文本
【发布时间】:2010-12-06 09:36:38
【问题描述】:

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

我想知道如何才能做到这一点,因为我对 Cocoa 绘图还很陌生。

【问题讨论】:

    标签: cocoa text drawing gradient


    【解决方案1】:

    尝试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 的信息)。

    【讨论】:

    • 谢谢!我还从 Apple 的 NSString 示例代码 (SpeedometerView) 中找到了一个类别,它将字符串转换为贝塞尔路径,剩下的就是简单地转换路径并用渐变填充它。
    猜你喜欢
    • 2018-06-30
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多