ios - 如何在图像周围添加笔触?

标签 ios core-graphics

问题

我有一张 CGImageRef 图片。它实际上是一个将用作 mask 的图像。所以,它的“alpha 层”才是我真正关心的。我想“加厚”图像的不透明部分,就好像我要在不透明部分周围添加笔触一样。如何做到这一点?

更多上下文

我有一个像这样的图像(CGImageRef):

enter image description here

它是由

创建的
    mask = CGBitmapContextCreateImage(context);

我把它当作面具使用。掩码下的 UIView 是相同的文本。问题是下面的文本没有被掩码覆盖。见:

enter image description here

更多代码

此代码在 UILabel 子类中。

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();

    // Draw text normally
    [super drawTextInRect:rect];

    if (self.alternativeTextColor) {
        CGImageRef mask = NULL;

        // Create a mask from the text
        mask = CGBitmapContextCreateImage(context);

        CGContextSaveGState(context);
        CGContextTranslateCTM(context, 0, self.frame.size.height);
        CGContextScaleCTM(context, 1.0, (CGFloat) -1.0);

        // Clip the current context to our mask
        CGContextClipToMask(context, rect, mask);

        // Set fill color
        CGContextSetFillColorWithColor(context, [self.alternativeTextColor CGColor]);

        // Path from mask
        CGPathRef path;

        if (CGRectIsEmpty(self.maskFrame)) {
            path = CGPathCreateMutable();
        } else {
            UIBezierPath *roundRectBezierPath = [UIBezierPath bezierPathWithRoundedRect:self.maskFrame
                                                                           cornerRadius:self.maskCornerRadius];
            path = CGPathCreateCopy([roundRectBezierPath CGPath]);
        }

        CGContextAddPath(context, path);

        // Fill the path
        CGContextFillPath(context);
        CFRelease(path);

        // Clean up
        CGContextRestoreGState(context);
        CGImageRelease(mask);
    }
}

项目链接

https://github.com/colasjojo/Test-NYSegmentedControl

最佳答案

如果您尝试剪切到文本,我建议不要通过中间位图来执行此操作,而是剪切到实际文本的路径,如下面来自 SVGgh 的 GHText 类的片段:

            CGContextSaveGState(quartzContext);
            CGContextSetTextDrawingMode(quartzContext, kCGTextStrokeClip);
            CGContextSetLineWidth(quartzContext, strokeWidthToUse);
            ... Draw Text here ....
             CGContextReplacePathWithStrokedPath(quartzContext);
            CGContextClip(quartzContext);
            ... Do clipped drawing here ...
            CGContextSetTextDrawingMode(quartzContext, kCGTextFill);
            CGContextRestoreGState(quartzContext);

这并没有回答您的问题,但这可能是您应该做的。尝试使用 CGContextSetTextDrawingMode 来获得您想要的效果。

关于ios - 如何在图像周围添加笔触?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32813941/

相关文章:

iphone - 当图像放大太大时,UIPinchGestureRecognizer 表现得很有趣

ios - 从 Swift 字典中检索 CGColor 时遇到问题

ios - 在没有 Init() 的情况下创建 UIView 子类 - Swift?

ios - cordova-plugin-mfp-push 导致 "unexpected Mach-O header"错误

objective-c - 在 UIPanGestureRecognizer 和重新启用的 UIScrollView 之间连续滚动

iOS 在一段时间不活动后执行操作(无用户交互)

ios - 如何在ios中限制UITextField的有限字符

swift - 在315°圆弧上绘制圆角

ios - swift 变得奇怪的淹没虚线

ios - 使用 Facebook Open Graph 发布操作