本文介绍了将边框放在CGContext上绘制的部分透明图像周围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的图像前景是黄色花瓶,透明背景:

I have an image with a yellow vase in the foreground and transparent background:

我在CGContext上绘制它:

I'm drawing it on a CGContext:

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

我可以在 CGContextDrawImage :

I can draw a shadow around it by using the following statement before CGContextDrawImage:

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

但是我想在图像周围画一个笔划,这样看起来就像下面这样:

But I want to put a stroke around the image, so that it'll looks like following:

如果我这样做:

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

它(显然)围绕整个iamge绘制一个矩形边框,如下所示:

It (obviously) draws a rectangular border around the whole iamge like this:

这不是我需要的。

但是在第三张图片中绘制边框的最佳方法是什么?

But what's the best way to draw the border as in the third image?

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

Please note that it's not possible to use UIImageView in this case, so using the properties of CALayer of UIImageView is not applicable.

推荐答案

这样做的一种方法是使用(所有来源都是麻省理工学院许可证,如果它对您有用)。

One way to do this is to use the mathematical morphology operator of dilation to "grow" the alpha channel of the image outward, then use the resulting grayscale image as a mask to simulate a stroke. By filling the dilated mask, then drawing the main image on top, you get the effect of a stroke. I've created a demo showing this effect, available on Github here: https://github.com/warrenm/Morphology (all source is MIT licensed, should it prove useful to you).

这里是它的实际截图:

请注意,这是非常缓慢的(扩张需要在每个像素上迭代内核),因此您应该选择笔划宽度并预先为每个源图像预先计算遮罩图像。

Note that this is staggeringly slow (dilation requires iteration of a kernel over every pixel), so you should pick a stroke width and precompute the mask image for each of your source images in advance.

这篇关于将边框放在CGContext上绘制的部分透明图像周围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 01:33