我想掩饰两个图像
图1:

图2:

现在我想合并这两个图像,像image2将出现在image1的中心。
我读过Any idea why this image masking code does not work?和"How to Mask an Image"
但在使用此函数时:
- (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage {
CGImageRef maskRef = maskImage.CGImage;
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef), NULL, false);
CGImageRef masked = CGImageCreateWithMask([image CGImage], mask);
return [UIImage imageWithCGImage:masked];
}但是通过使用这个函数,我得到的输出是:

发布于 2013-05-25 23:37:09
据我所知,问题不在maskImage:withMask:。您发布的错误输出没有错:在image1的像素是黑色的地方,image2是不可见的。
问题可能出在用于加载image和mask的函数中,也可能出在生成图形输出的代码中。实际上,在我看来,你得到了正确的输出,但使用了错误的色彩空间(没有alpha的灰度)。检查您提供的参数image是否实际为RGBa格式,以及返回的UIImage是否未使用DeviceGray作为色彩空间绘制到其他CGContext上。
我想到的另一个可能的原因是你颠倒了image1和image2。根据文档,mask应该扩展到image的大小(见下文),但您有一个小图像。这似乎也是合理的,因为image1是灰度的,尽管当我试图交换image1和image2时,我得到了未经修改的image1作为输出。
为了运行测试,我使用了附加的图像,然后按原样复制并粘贴了方法-(UIImage *)maskImage:(UIImage *)image withMask:(UIImage *)maskImage。
我使用了一个简单的iOS项目,其中有一个视图和一个UIImageView (带有标记1),控制器中有以下代码:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIImageView *imageView=(UIImageView *)[self.view viewWithTag:1];
UIImage *im1=[UIImage imageNamed:@"image1"];
UIImage *im2=[UIImage imageNamed:@"image2"];
imageView.image=[self maskImage:im2 withMask:im1];
}我得到以下输出(这是正确的):

如果你错误地用im2颠倒了im1,你得到的是未修改的image1。
https://stackoverflow.com/questions/8488062
复制相似问题