OGeek|极客世界-中国程序员成长平台

标题: iphone - 描边同时应用于文本和阴影 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 22:15
标题: iphone - 描边同时应用于文本和阴影

我试图简单地用笔画绘制一些文本,然后应用阴影,但笔画正在应用于阴影。如何防止这种情况发生?

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];



Best Answer-推荐答案


因为你的文字绘制模式是kCGTextFillStrokeCGContextShowTextAtPoint是先绘制填充(并为其生成阴影),然后绘制描边(得到自己的阴影)。

要修复它,请使用 transparency layer .

请注意,如果您使用 CGContextBeginTransparencyLayerWithRect() 并传入尽可能小的矩形,它会绘制得更快。

或者:如果它是一个足够好的近似值,您可以考虑分两步绘制文本:

  1. 用阴影填充
  2. 描边,没有阴影

如果你的笔画很小,差异不会很明显,而且会画得更快。

关于iphone - 描边同时应用于文本和阴影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9816222/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4