2012-03-22 32 views
2

我想簡單地繪製一些文字與筆畫,然後應用陰影,但筆畫正在應用投影。我如何防止這種情況?筆畫正在應用於文字和陰影

Notice stroke is applied to drop shadow

// Setup context 
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst); 

// draw photo into context 
CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage); 
// Set Text Font 
CGContextSelectFont(context, font.fontName.UTF8String, fontSize, kCGEncodingMacRoman); 

// Set Text Drawing Mode 
CGContextSetTextDrawingMode(context, kCGTextFillStroke); 

// Set text fill color 
CGColorRef tmpColor = color.CGColor; 
CGFloat newComponents[4] = {}; 
memcpy(newComponents, CGColorGetComponents(tmpColor), sizeof(newComponents)); 
CGContextSetRGBFillColor(context, newComponents[0], newComponents[1], newComponents[2], newComponents[3]); 

// Calculate Height 
UIFont *testFont = [UIFont fontWithName:font.fontName size:fontSize]; 
CGSize size = [text sizeWithFont:testFont]; 

// Setup Font Shadow 
CGSize shadowSize = CGSizeMake(6, 6); 
CGContextSetShadowWithColor(context, shadowSize, 1.0, [[UIColor darkGrayColor] CGColor]); 

// Set Stroke Color 
CGContextSetRGBStrokeColor(context, 0, 255, 0, 1); 
CGContextSetLineWidth(context, 2.0); 

// draw text at location centered based on width. 
CGContextShowTextAtPoint(context, (w/2) - (textWidth/2), h - size.height, ctext, strlen(ctext)); 

// Render Bitmap 
CGImageRef imageMasked = CGBitmapContextCreateImage(context); 
UIImage *returnImage = [UIImage imageWithCGImage:imageMasked]; 

回答

2

因爲你的文字繪製模式kCGTextFillStrokeCGContextShowTextAtPoint首先繪製填充(和產生陰影效果的話),然後繪製行程(這都有自己的影子)。請使用transparency layer

請注意,如果您使用CGContextBeginTransparencyLayerWithRect()並以儘可能小的方式傳入,它將會快得多。

另外:如果它是一個足夠好的近似,則可以考慮繪製文本分爲兩步:

  1. 填充,陰影
  2. 行程,沒有陰影

如果你的行程很小,差別不會很明顯,而且會畫得快得多。

+0

很好用!我只是在我的影子後添加了CGContextBeginTransparencyLayer,然後在我的Stroke和SetText後添加了CGContextEndTransparencyLayer。謝謝! – KevinS 2012-03-22 04:40:37

+0

好。我真的強烈建議通過一個直接的通過;陰影繪圖是你在iOS上可以做的最昂貴的事情之一,而透明度圖層特別糟糕,因爲CG必須創建一個與整個上下文大小相同的臨時緩衝區,併爲整個事物生成一個陰影。限制圖層大小是您可以製作的最佳和最簡單的優化之一。 – 2012-03-22 04:54:52

+0

好吧,我會盡力做到這一點。我已經遇到了一些內存問題,因爲我的上下文來自UIImagePickerView拍攝的照片,並且帶有4S後置攝像頭,分辨率非常高! – KevinS 2012-03-22 05:22:35