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 对象示例)
当我将上面的代码更改为 [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];
结果会是这样的。
关于iOS UIImage mask 边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23515462/