【问题标题】:Stroke is being applied to both Text and Shadow描边同时应用于文本和阴影
【发布时间】:2012-03-22 03:55:26
【问题描述】:

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

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

【问题讨论】:

    标签: iphone ios quartz-graphics quartz-2d


    【解决方案1】:

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

    要修复它,请使用transparency layer

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

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

    1. 用阴影填充
    2. 中风,没有阴影

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

    【讨论】:

    • 效果很好!我只是在我的阴影之后添加了 CGContextBeginTransparencyLayer,然后在我的 Stroke 和 SetText 之后添加了 CGContextEndTransparencyLayer。谢谢!
    • 好。我真的强烈建议通过一个矩形;阴影绘制是您在 iOS 上可以做的最昂贵的事情之一,透明层尤其糟糕,因为 CG 必须制作一个与整个上下文大小相同的临时缓冲区并为整个事物生成阴影。限制层大小是您可以进行的最佳和最简单的优化之一。
    • 好的,我会尝试这样做。我已经遇到了一些内存问题,因为我的上下文来自 UIImagePickerView 拍摄的照片,并且使用 4S 后置摄像头分辨率非常高!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-08
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    相关资源
    最近更新 更多