Обратное маскирование изображения

В IOS SDK я могу замаскировать изображение, но не могу изменить маску изображения. я имею в виду, что у меня есть одно изображение, которое имеет прямоугольную часть, и теперь я маскирую изображение, и я получаю прикрепленное изображение, но я хочу получить обратный результат.

В результате я получаю изображение. введите здесь описание изображения

пока мне это нужно как результат.

введите здесь описание изображения

Пожалуйста, помогите мне достичь этого.

... Редактировать... Мой код

 UIGraphicsBeginImageContextWithOptions(self.imageView.frame.size, NO, 0.0);
CGContextRef context = UIGraphicsGetCurrentContext();

CGContextTranslateCTM(context, 0.0, self.imageView.frame.size.height);
CGContextScaleCTM(context, 1.0, -1.0);

CGImageRef maskImage = [[UIImage imageNamed:@"2.png"] CGImage];
CGContextClipToMask(context, self.imageView.bounds, maskImage);

   CGContextTranslateCTM(context, 0.0, self.imageView.frame.size.height);
   CGContextScaleCTM(context, 1.0, -1.0);

[[self.imageView image] drawInRect:self.imageView.bounds];

UIImage *image11 = UIGraphicsGetImageFromCurrentImageContext();

self.imageView.image = image11;

Спасибо


person Hindu    schedule 17.08.2013    source источник
comment
Как вы замаскировали изображение? Покажи свой код!   -  person Martin R    schedule 17.08.2013
comment
Пожалуйста, посмотрите на это. я отредактировал свой вопрос и добавил свой код..   -  person Hindu    schedule 17.08.2013
comment
Нельзя ли просто нарисовать изображение, а затем нарисовать над ним белый прямоугольник?   -  person Wain    schedule 17.08.2013
comment
Спасибо, но это не белый прямоугольник. это цвет фона при просмотре   -  person Hindu    schedule 17.08.2013


Ответы (1)


Я достиг этого в два шага. Возможно, это не лучший способ сделать это, но он работает.

  1. Инвертируйте изображение маски.
  2. Маска

Посмотрите на код ниже.

 - (void)viewDidLoad
{
    [super viewDidLoad];

    _imageView = [[UIImageView alloc] initWithImage:i(@"test1.jpg")];
    _imageView.image = [self maskImage:i(@"face.jpg") withMask:[self negativeImage]];
    [self.view addSubview:_imageView];
}

Метод ниже взят из здесь

- (UIImage *)negativeImage
{
    // get width and height as integers, since we'll be using them as
    // array subscripts, etc, and this'll save a whole lot of casting
    CGSize size = self.imageView.frame.size;
    int width = size.width;
    int height = size.height;

    // Create a suitable RGB+alpha bitmap context in BGRA colour space
    CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char *memoryPool = (unsigned char *)calloc(width*height*4, 1);
    CGContextRef context = CGBitmapContextCreate(memoryPool, width, height, 8, width * 4, colourSpace, kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast);
    CGColorSpaceRelease(colourSpace);

    // draw the current image to the newly created context
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), [self.imageView.image CGImage]);

    // run through every pixel, a scan line at a time...
    for(int y = 0; y < height; y++)
    {
        // get a pointer to the start of this scan line
        unsigned char *linePointer = &memoryPool[y * width * 4];

        // step through the pixels one by one...
        for(int x = 0; x < width; x++)
        {
            // get RGB values. We're dealing with premultiplied alpha
            // here, so we need to divide by the alpha channel (if it
            // isn't zero, of course) to get uninflected RGB. We
            // multiply by 255 to keep precision while still using
            // integers
            int r, g, b;
            if(linePointer[3])
            {
                r = linePointer[0] * 255 / linePointer[3];
                g = linePointer[1] * 255 / linePointer[3];
                b = linePointer[2] * 255 / linePointer[3];
            }
            else
                r = g = b = 0;

            // perform the colour inversion
            r = 255 - r;
            g = 255 - g;
            b = 255 - b;

            // multiply by alpha again, divide by 255 to undo the
            // scaling before, store the new values and advance
            // the pointer we're reading pixel data from
            linePointer[0] = r * linePointer[3] / 255;
            linePointer[1] = g * linePointer[3] / 255;
            linePointer[2] = b * linePointer[3] / 255;
            linePointer += 4;
        }
    }

    // get a CG image from the context, wrap that into a
    // UIImage
    CGImageRef cgImage = CGBitmapContextCreateImage(context);
    UIImage *returnImage = [UIImage imageWithCGImage:cgImage];

    // clean up
    CGImageRelease(cgImage);
    CGContextRelease(context);
    free(memoryPool);

    // and return
    return returnImage;
}

Приведенный ниже метод взят из здесь.

- (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];

}
person Vignesh    schedule 17.08.2013
comment
Спасибо, Вигнеш, я попробовал ваш код, но получил тот же результат с инвертированным цветом... есть ли у вас какие-либо предложения... - person Hindu; 17.08.2013
comment
Попробуйте распечатать перевернутое изображение маски и проверьте, инвертирует ли оно альфа-канал вашей маски. Другой способ — построить путь (используя кривые Безье) и сделать EO Clip. Я также могу поделиться своим изображением маски, если вам это нужно. - person Vignesh; 18.08.2013
comment
Привет... Не могли бы вы предложить какое-либо решение для IOS 7. Потому что оно не работает на IOS 7.... - person Hindu; 25.09.2013
comment
Любая идея об обратной маскировке. (Мне нужна прозрачная область с заливкой.) В приведенном выше методе он дает только область маски .... пожалуйста, помогите мне. - person Milan patel; 23.01.2015
comment
Инверсия цветов не имеет ничего общего с маскировкой изображения. Как это стало принятым ответом? - person buildsucceeded; 15.04.2016