ios - 在 CGContext 上绘制的部分透明图像周围放置边框

标签 ios core-graphics cgcontext cgcontextdrawimage

我有一张图片,前景是黄色花瓶,背景是透明的:

enter image description here

我在 CGContext 上绘制它:

CGContextDrawImage(context, CGRectMake(0, 0, 100, 100), myImage.CGImage);

我可以在 CGContextDrawImage 之前使用以下语句在其周围绘制阴影:

CGContextSetShadowWithColor(context, CGSizeMake(0,0), 5, [UIColor blueColor].CGColor);

enter image description here

但我想在图像周围画笔画,这样它看起来像下面这样:

enter image description here

如果我这样做:

CGContextSetRGBStrokeColor(shadowContext, 0.0f, 0.0f, 1.0f, 1.0f);
CGContextSetLineWidth(shadowContext, 5);
CGContextStrokeRect(shadowContext, CGRectMake(0, 0, 100, 100));

它(显然)在整个图像周围绘制了一个矩形边框,如下所示:

enter image description here

这不是我需要的。

但是像第三张图片那样绘制边框的最佳方式是什么?

请注意,在这种情况下无法使用 UIImageView,因此无法使用 UIImageView 的 CALayer 属性。

最佳答案

一种方法是使用 mathematical morphology operator of dilation向外“增长”图像的 Alpha channel ,然后使用生成的灰度图像作为蒙版来模拟笔划。通过填充扩张的蒙版,然后在顶部绘制主图像,您可以获得笔划的效果。我创建了一个展示这种效果的演示,可在 Github 上获取:https://github.com/warrenm/Morphology (如果证明对您有用,所有来源均已获得麻省理工学院许可)。

这是它的实际截图:

enter image description here

请注意,这非常慢(膨胀需要在每个像素上迭代内核),因此您应该选择笔划宽度并预先为每个源图像预先计算掩码图像。

关于ios - 在 CGContext 上绘制的部分透明图像周围放置边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14902444/

相关文章:

iphone - 如何相对于屏幕 iPhone 的一侧锚定 View

swift - XCode 错误导入库

ios - CAGradient 图层在 View 中不可见

ios - CGContextSetLineDash不可用

ios - singleton swift 的困难

iphone - iOS 上的 "Terminating app due to uncaught exception"

ios - 为 CoreText 创建 CGContext

iphone - 将图像部分转换为黑白效果

android - 在增强现实应用程序中变换屏幕上的纬度、经度位置

ios - 根据时间戳计算动画中风开始?