CGContextRef context = [[NSGraphicsContext currentContext] graphicsPort];
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0.0f, self.bounds.size.height);
CGContextScaleCTM(context, 1.0f, -1.0f);
CGContextSelectFont(context, "Helvetica", 20.0f, kCGEncodingMacRoman);
CGContextSetTextDrawingMode(context, kCGTextClip);
CGContextSetTextPosition(context, 0.0f, round(20.0f / 4.0f));
//这个函数不能显示中文。。。。
CGContextShowText(context, [_content UTF8String], strlen([_content UTF8String]));
CGContextClip(context);
CGGradientRef gradient;
CGColorSpaceRef rgbColorspace;
size_t num_locations = 2;
CGFloat locations[2] = { 0.0, 1.0 };
CGFloat components[8] = { 1.0, 1.0, 1.0, 1.0, // Start color
1.0, 1.0, 1.0, 0.1 }; // End color
rgbColorspace = CGColorSpaceCreateDeviceRGB();
gradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);
CGRect currentBounds = self.bounds;
CGPoint topCenter = CGPointMake(CGRectGetMidX(currentBounds), 0.0f);
CGPoint midCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMidY(currentBounds));
CGContextDrawLinearGradient(context, gradient, topCenter, midCenter, 0);
CGGradientRelease(gradient);
CGColorSpaceRelease(rgbColorspace);
CGContextRestoreGState(context);
上面这段代码使用Core Graphics来绘制渐渐色文字,但是有个致命的缺点:CGContextShowText 这个方法不能显示Unicode 编码的文字,因此也无法显示中文。
Core Graphics 这套API中只有CGContextShowText 这个显示文字的方法,所以不得不改用其他的方案。后来,发现了一个比较取巧的解决办法:
将渐进色绘制到空白的图片(Bitmap)上,然后调用 + (NSColor *)colorWithPatternImage:(NSImage*)image; ,传入上面生成的图片,即可得到颜色值,将得到的颜色值设给文字的NSForegroundColorAttributeName 属性。下面来看看具体实现的代码。
将通过渐渐色生成NSImage这些逻辑写在了 NSImage+Gradient 这个类中,NSImage+Gradient.m 实现如下:
#import "NSImage+Gradient.h"
@implementation NSImage (Gradient)
/**
* @method
* @abstract 生成渐进色背景图片
* @discussion
* @param gradientColors 渐进色数组 imageSize:要生成的图片的大小
* @result NSImage :返回生成的图片
*/
+ (NSImage *)gradientImageWithColors:(NSArray *)gradientColors imageSize:(NSSize)imageSize {
if (gradientColors == nil || NSEqualSizes(imageSize, NSZeroSize)) {
return nil;
}
NSBitmapImageRep * bitmapRep = nil;
NSImage *image = nil;
if (imageSize.width > 0 && imageSize.height > 0) {
int pixelsWide = imageSize.width, pixelsHigh = imageSize.height;
CGContextRef ctx = NULL;
bitmapRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: nil // Nil pointer makes the kit allocate the pixel buffer for us.
pixelsWide: pixelsWide // The compiler will convert these to integers, but I just wanted to make it quite explicit
pixelsHigh: pixelsHigh //
bitsPerSample: 8
samplesPerPixel: 4 // Four samples, that is: RGBA
hasAlpha: YES
isPlanar: NO // The math can be simpler with planar images, but performance suffers..
colorSpaceName: NSCalibratedRGBColorSpace // A calibrated color space gets us ColorSync for free.
bytesPerRow: pixelsWide * 4
bitsPerPixel: 32]; // This must agree with bitsPerSample and samplesPerPixel.;
if (bitmapRep) {
ctx = CGBitmapContextCreate([bitmapRep bitmapData], [bitmapRep size].width, [bitmapRep size].height, [bitmapRep bitsPerSample], [bitmapRep bytesPerRow], [[bitmapRep colorSpace] CGColorSpace], kCGImageAlphaPremultipliedLast);
}
if (ctx) {
CGContextSaveGState(ctx);
//draw gradient
CGGradientRef gradient;
CGColorSpaceRef rgbColorspace;
//set uniform distribution of color locations
size_t num_locations = [gradientColors count];
CGFloat locations[num_locations];
for (int k=0; k<num_locations; k++) {
locations[k] = k / (CGFloat)(num_locations - 1); //we need the locations to start at 0.0 and end at 1.0, equaly filling the domain
}
//create c array from color array
CGFloat components[num_locations * 4];
for (int i=0; i<num_locations; i++) {
NSColor *color = [gradientColors objectAtIndex:i];
// NSAssert(color.canProvideRGBComponents, @"Color components could not be extracted from StyleLabel gradient colors.");
components[4*i+0] = [color redComponent];
components[4*i+1] = [color greenComponent];
components[4*i+2] = [color blueComponent];
components[4*i+3] = [color alphaComponent];
}
rgbColorspace = CGColorSpaceCreateDeviceRGB();
gradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);
CGPoint topCenter = CGPointMake(0, 0);
CGPoint bottomCenter = CGPointMake(0, imageSize.height);
CGContextDrawLinearGradient(ctx, gradient, topCenter, bottomCenter, 0);
CGGradientRelease(gradient);
CGColorSpaceRelease(rgbColorspace);
// pop context
CGContextRestoreGState(ctx);
}
if (ctx) {
CGContextRelease(ctx); ctx = nil;
}
}
if (bitmapRep) {
image = [[NSImage alloc] initWithData:[bitmapRep TIFFRepresentation]];
[bitmapRep release]; bitmapRep = nil;
}
return [image autorelease];
}
@end
然后,定义了NSView的一个子类用来绘制和显示渐渐色文字。
MyGradientTextView.h
#import <Cocoa/Cocoa.h>
@interface MyGradientTextView : NSView {
NSString *_content;
NSMutableDictionary *_textAttr;
}
- (void)setContent:(NSString *)content;
@end
MyGradientTextView.m
#import "MyGradientTextView.h"
#import "NSImage+Gradient.h"
@implementation MyGradientTextView
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
_textAttr = [[NSMutableDictionary alloc] init];
//Lucida Grande
[_textAttr setValue:[NSFont fontWithName:@"HelveticaNeue-Bold" size:75] forKey:NSFontAttributeName];
[_textAttr setValue:[NSColor greenColor] forKey:NSForegroundColorAttributeName];
// [_textAttr setValue:[NSNumber numberWithFloat:-1] forKey:NSStrokeWidthAttributeName];//轮廓宽度
[_textAttr setValue:[NSColor blackColor] forKey:NSStrokeColorAttributeName];//轮廓颜色
NSShadow *shadow = [[NSShadow alloc] init];
[shadow setShadowColor: [NSColor blackColor]];
[shadow setShadowBlurRadius: 1];
[shadow setShadowOffset: NSMakeSize( 0, -1)];
[_textAttr setValue:shadow forKey:NSShadowAttributeName];
[shadow release];
NSMutableParagraphStyle* paraStyle = [[NSMutableParagraphStyle alloc] init];
[paraStyle setAlignment:NSCenterTextAlignment];
[paraStyle setLineBreakMode:NSLineBreakByWordWrapping];
[_textAttr setValue:paraStyle forKey:NSParagraphStyleAttributeName];
[paraStyle release];
}
return self;
}
- (void)dealloc
{
[_content release];
[_textAttr release];
[super dealloc];
}
- (void)drawRect:(NSRect)dirtyRect
{
if (_content) {
NSSize textSize = [_content sizeWithAttributes:_textAttr];
//自己可根据需要来配置颜色数组
NSArray *colorArray = [NSArray arrayWithObjects:
[NSColor colorWithDeviceRed:255/255.0 green:128/255.0 blue:0/255.0 alpha:1.0],
[NSColor colorWithDeviceRed:255/255.0 green:210/255.0 blue:79/255.0 alpha:1.0],
[NSColor colorWithDeviceRed:140/255.0 green:198/255.0 blue:63/255.0 alpha:1.0],nil];
//关键在这里了
NSImage *graidentImage = [NSImage gradientImageWithColors:colorArray imageSize:textSize];
NSColor *textColor = [NSColor colorWithPatternImage:graidentImage];
[_textAttr setValue:textColor forKey:NSForegroundColorAttributeName];
NSRect drawRect = NSMakeRect(NSMinX(self.bounds), NSMinY(self.bounds), textSize.width, textSize.height);
[_content drawInRect:drawRect withAttributes:_textAttr];
}
}
- (void)setContent:(NSString *)content {
[content retain];
[_content release];
_content = content;
[self setNeedsDisplay:YES];
}
@end
最后,绘制出来的效果如下:
完整代码: DrawGradientText