我想在 iOS 中的两个图像之间进行选择性遮罩,类似于 Blender 中的遮罩功能。有两个图像 1 和 2(调整为相同的尺寸)。最初只有图像 1 是可见的,但是无论用户在哪里触摸 image1 上的任何区域,它都会变得透明,并且图像 2 在这些区域中变得可见。
我使用带有触摸移动的核心图形创建了一个类似蒙版的图像。它基本上是一个全黑的图像,在我触摸的任何地方都有白色部分。alpha 始终设置为 1.0。我可以使用这个图像作为掩码,并通过实现我自己的图像处理方法来做必要的事情,这些方法将遍历每个像素,检查它并设置相应的值。现在这个方法将在 touch move 内部调用,所以我的方法可能会减慢整个过程(特别是对于 8MP 相机图像)。
我想知道如何通过使用 Quartz Core 或 Core Graphics 来实现这一点,它们的效率足以在大图像中运行。
我到目前为止的代码:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
mouseSwiped = YES;
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:staticBG];
UIGraphicsBeginImageContext(staticBG.frame.size);
[maskView.image drawInRect:CGRectMake(0, 0, maskView.frame.size.width, maskView.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 20.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 1.0, 1.0, 0.0);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
maskView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
lastPoint = currentPoint;
mouseMoved++;
if (mouseMoved == 10)
mouseMoved = 0;
staticBG.image = [self maskImage:staticBG.image withMask:maskView.image];
//maskView.hidden = NO;
}
- (UIImage*) maskImage:(UIImage *)baseImage withMask:(UIImage *)maskImage
{
CGImageRef imgRef = [baseImage CGImage];
CGImageRef maskRef = [maskImage CGImage];
CGImageRef actualMask = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef), NULL, false);
CGImageRef masked = CGImageCreateWithMask(imgRef, actualMask);
return [UIImage imageWithCGImage:masked];
}
maskImage 方法不起作用,因为它根据 alpha 值创建掩码图像。我浏览了这个链接:从路径创建蒙版,但我无法理解答案。