iOS UIImage mask 边框

标签 ios objective-c uiimage core-graphics

iOS 有没有办法为不是简单矩形的图像添加边框?

我已使用以下代码成功对图像进行了着色:

- (UIImage *)imageWithTintColor:(UIColor *)tintColor
{
    UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextTranslateCTM(context, 0, self.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextSetBlendMode(context, kCGBlendModeNormal);

    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    CGContextClipToMask(context, rect, self.CGImage);

    [tintColor setFill];
    CGContextFillRect(context, rect);

    UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return tintedImage;
}

举例来说,我想向该图像添加蓝色边框(注意:这不是一个“A”NSString,而是一个 UIImage 对象示例)

enter image description here

当我将上面的代码更改为 [color setStroke]CGContextStrokeRect(context, rect) 时,图像就消失了。

我已经从 SO 了解到,使用 CoreImage + EdgeDetection 可以做到这一点,但是没有一个“简单”的 CoreGraphics - 类似于对图像着色的方式吗?

谢谢!

-- 编辑 --

请注意,我想为图像本身添加边框。我不想通过 UIImageView 创建边框效果!

在应用边框之前,边框应与图像的形状相匹配。 在本例中:“A”的外部 + 内部为蓝色轮廓。

最佳答案

我想说,这不是一个非常令人满意的方法,但在某种程度上有效。

您可以利用向图层添加阴影。为此,您需要去掉图像中的白色部分,让字符被 Alpha 包围。

我使用了下面的代码。

UIImage *image = [UIImage imageNamed:@"image_name_here.png"];

CALayer *imageLayer = [CALayer layer];
imageLayer.frame = CGRectMake(0, 0, 200.0f, 200.0f);
imageLayer.contents = (id)image.CGImage;
imageLayer.position = self.view.layer.position;

imageLayer.shadowColor = [UIColor whiteColor].CGColor;
imageLayer.shadowOffset = CGSizeMake(0.0f, 0.0f);
imageLayer.shadowOpacity = 1.0f;
imageLayer.shadowRadius = 4.0f;

[self.view.layer addSublayer:imageLayer];

结果会是这样的。

And the result would be

关于iOS UIImage mask 边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23515462/

相关文章:

ios - UIAlertController 因在 backgroundThread Objective-C 中出现而崩溃

ios - 从视频生成缩略图最终总是在 UIImageView 中旋转

iphone - 如何从pdf文件中的FileAttachment Annotation获取图像

iphone - 从数组中删除重复项,比较其对象的属性

ios - UITableviewCell 中的图像

ios - 将 UIImage View 从 A 点移动到 B 点的最简单代码

尝试使用权限时,使用 Adob​​e AIR SDK 24 构建的 iOS 应用程序崩溃

iOS Swift 后台位置监控

ios - 如何为现有的 iOS 应用程序添加 CarPlay 支持?

iphone - 初始化与文件内容 :path] memory management when returns nil