ios - 在 iOS 中用另一个实际图像掩盖透明图像

标签 ios objective-c image

我有两张图像,一张是带有一些边缘/边框的透明蒙版,另一张是实际图像。我想合并它们。

enter image description here enter image description here

我使用以下代码来屏蔽和组合图像:

 - (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage {

    // create a bitmap graphics context the size of the image
    CGFloat dim = MIN(image.size.width, image.size.height);
    CGSize size = CGSizeMake(dim, dim);
    UIGraphicsBeginImageContextWithOptions(size, NO, .0);
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithOvalInRect:(CGRect){ CGPointZero, size }];
    [bezierPath fill];
    [bezierPath addClip];
    CGPoint offset = CGPointMake((dim - image.size.width) * 0.5, (dim - image.size.height) * 0.5);
    [image drawInRect:(CGRect){ offset, image.size }];
    UIImage *ret = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return ret;
}

结果:

enter image description here

在结果图像中,用作掩码的图像的边框缺失 .有人可以帮我吗?

最佳答案

我为 ios 编写了一个 mask 类别(好吧,它基本上是跨平台的,因为 CoreImage 无论如何都在两个平台上:

github project

核心功能归结为这一点(例如)

UIImage *person = ...
UIImage *circle = ...
UIImage *result = [person imageMaskedWith:circle];

UIImageView *redbox = [[UIImageView alloc] initWithImage:result];
redbox.backgroundColor = [UIColor redColor]; //this can be a gradient!

来自类的主要部分代码:
CGImageRef imageReference = image.CGImage;
CGImageRef maskReference = mask.CGImage;
CGRect rect = CGRectMake(0, 0, CGImageGetWidth(imageReference), CGImageGetHeight(imageReference));

// draw with Core Graphics
UIGraphicsBeginImageContext(rect.size);
CGContextRef bitmap = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(bitmap, 0.0, rect.size.height);
CGContextScaleCTM(bitmap, 1.0, -1.0);

CGContextClipToMask(bitmap, rect, maskReference);
CGContextDrawImage(bitmap, rect, imageReference);

newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

关于ios - 在 iOS 中用另一个实际图像掩盖透明图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28133120/

相关文章:

ios - 如何以编程方式向 UINavigationBar 添加后退按钮?

objective-c - 线程1 :EXC_BAd_InSTRUCTION(code =EXC_1386_INVOP,子代码)

iphone - 调用实例方法通常比调用类方法更快吗?

objective-c - 如何清除ipad中的webview缓存

ios - 在卸载/重新安装应用程序之间以编程方式清除 NSUserDefaults 数据库

ios - 在 iOS 中将图像大小减小至最大 100 kb,并固定尺寸 512x512

javascript - 我的脚本无法仅循环 5 个图像一次

ios - UIImagePickerControllerEditedImage 与图像选择器 View 中的图像不匹配

iphone - ARC 中的 '[[something retain] autorelease]' 是什么?

java - 在 JFrame 中设置背景图像