菜鸟教程小白 发表于 2022-12-13 07:42:53

iOS UIImage蒙版边框


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

<p>我已使用以下代码成功为图像着色:</p>

<pre><code>- (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);

    ;
    CGContextFillRect(context, rect);

    UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return tintedImage;
}
</code></pre>

<p>比如说我想给这张图片添加一个蓝色边框(注意:这不是一个 'A' NSString,而是一个 UIImage 对象示例)</p>

<p> <img src="/image/53327.png" alt="enter image description here"/> </p>

<p>当我将上面的代码更改为 <code></code> 和 <code>CGContextStrokeRect(context, rect)</code> 时,图像就消失了。</p>

<p>我已经从 SO 那里了解到,使用 CoreImage + EdgeDetection 可以实现这一点,但难道没有“简单”的 CoreGraphics - 类似于给图像着色的方式吗?</p>

<p>谢谢!</p>

<p>-- <strong>编辑</strong>--</p>

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

<p>在应用边框之前,边框应与图像的形状相匹配。
在这种情况下:“A”的外部 + 内部的蓝色轮廓。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>我会说这不是一个非常令人满意的方法,但在某种程度上有效。</p>

<p>您可以使用向图层添加阴影。为此,您需要去除图像中的白色部分,让字符被 alpha 包围。</p>

<p>我使用了下面的代码。</p>

<pre><code>UIImage *image = ;

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

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

;
</code></pre>

<p>结果会是这样的。</p>

<p> <img src="/image/ct6fJ.png" alt="And the result would be"/> </p></p>
                                   
                                                <p style="font-size: 20px;">关于iOS UIImage蒙版边框,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/23515462/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/23515462/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: iOS UIImage蒙版边框