3

这是我正在做的动态屏蔽 UIImage 的操作。它正在工作,但由于某种原因,输出图像的颜色与原始图像的颜色不同。什么会导致这种情况?谢谢..

- (void) setClippingPath:(UIBezierPath *)clippingPath : (UIImageView *)imgView {

    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = self.imgView.frame;
    maskLayer.path = [clippingPath CGPath];
    maskLayer.fillColor = [[UIColor whiteColor] CGColor];
    maskLayer.backgroundColor = [[UIColor clearColor] CGColor];

    self.imgView.image =  [self maskImage:self.imgView.image withClippingMask:[self imageFromLayer:maskLayer]];

}


- (UIImage *)imageFromLayer:(CALayer *)layer
{
    UIGraphicsBeginImageContext([layer frame].size);

    [layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return outputImage;
}

-(UIImage*)maskImage:(UIImage *)image withClippingMask:(UIImage *)maskImage
{
    CGImageRef maskRef = image.CGImage;

    CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
                                        CGImageGetHeight(maskRef),
                                        CGImageGetBitsPerComponent(maskRef),
                                        CGImageGetBitsPerPixel(maskRef),
                                        CGImageGetBytesPerRow(maskRef),
                                        CGImageGetDataProvider(maskRef), NULL, false);

    CGImageRef maskedImageRef = CGImageCreateWithMask([maskImage CGImage], mask);
    UIImage *maskedImage = [UIImage imageWithCGImage:maskedImageRef];

    CGImageRelease(mask);
    CGImageRelease(maskedImageRef);

    // returns new image with mask applied
    return maskedImage;

}

原始图像

在此处输入图像描述

面具

在此处输入图像描述

输出图像

在此处输入图像描述

在此处输入图像描述

4

1 回答 1

1

CGImageMaskCreate 的文档提到:

当您使用位图图像掩码绘制到上下文中时,Quartz 使用掩码来确定当前填充颜色应用于图像矩形的位置和方式。

因此,如果您只想用白色替换黑色,那么您应该能够在创建蒙版之前设置上下文颜色:

-(UIImage*)maskImage:(UIImage *)image withClippingMask:(UIImage *)maskImage
{
    CGImageRef maskRef = image.CGImage;

    CGContextSetFillColorWithColor( UIGraphicsGetCurrentContext( ), [ UIColor whiteColor ] );
    CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
                                        CGImageGetHeight(maskRef),
                                        CGImageGetBitsPerComponent(maskRef),
                                        CGImageGetBitsPerPixel(maskRef),
                                        CGImageGetBytesPerRow(maskRef),
                                        CGImageGetDataProvider(maskRef), NULL, false);

    CGImageRef maskedImageRef = CGImageCreateWithMask([maskImage CGImage], mask);
    UIImage *maskedImage = [UIImage imageWithCGImage:maskedImageRef];

    CGImageRelease(mask);
    CGImageRelease(maskedImageRef);

    // returns new image with mask applied
    return maskedImage;
}

您可能还想将您的蒙版更新为更基本的灰度 JPG,如下所示:

在此处输入图像描述

于 2013-08-27T04:09:26.837 回答