Маскировка изображений и создание нового UIImage

Вот проблема, с которой я сталкиваюсь:

Я реализовал маскирование с использованием maskimage.

Вот исходное изображение: (размер: 300width x 418height)

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

Вот изображение маски: (Размер: ширина 165 x 215 высота)

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

Ниже приведен код, который я использовал для обрезки изображения в соответствии с маской и создания нового UIImage:

CALayer *mask = [CALayer layer];
mask.contents = (id)[[UIImage imageNamed:@"maskImage.png"] CGImage];
mask.frame = imgMaskImage.frame;
mask.frame = CGRectMake(mask.frame.origin.x-10, mask.frame.origin.y-50, mask.frame.size.width, mask.frame.size.height);
self.imgEditedImageView.layer.mask = mask;
self.imgEditedImageView.layer.masksToBounds = YES;
imgMaskImage.image = nil;

UIGraphicsBeginImageContext(self.imgEditedImageView.frame.size);
[self.imgEditedImageView.layer renderInContext:UIGraphicsGetCurrentContext()];
croppedImage = UIGraphicsGetImageFromCurrentImageContext();
[croppedImage drawInRect:imgMaskImage.frame];
UIGraphicsEndImageContext();

Это работает и обрезает изображение соответственно. Вот результат:

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

Но выпуск финального изображения croppedImage(UIImage) занимает кадр исходного изображения (300x418).

Я не понимаю, почему это происходит. Я пробовал так много вещей, но до сих пор нет решения. Может ли кто-нибудь, пожалуйста, предложить мне, если я делаю что-то не так или что-то не так.

Благодарю.

1 ответ

Решение
- (UIImage *)croppedPhoto {
    // For dealing with Retina displays as well as non-Retina, we need to check
   // the scale factor, if it is available. Note that we use the size of teh cropping Rect
    // passed in, and not the size of the view we are taking a screenshot of.
     CGRect croppingRect = CGRectMake(imgMaskImage.frame.origin.x,
    imgMaskImage.frame.origin.y, imgMaskImage.frame.size.width,
    imgMaskImage.frame.size.height);

    imgMaskImage.hidden=YES;

    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
        UIGraphicsBeginImageContextWithOptions(croppingRect.size, YES,
    [UIScreen mainScreen].scale);
    } else {
        UIGraphicsBeginImageContext(croppingRect.size);
    }

    // Create a graphics context and translate it the view we want to crop so
    // that even in grabbing (0,0), that origin point now represents the actual
    // cropping origin desired:
         CGContextRef ctx = UIGraphicsGetCurrentContext();
         CGContextTranslateCTM(ctx, -croppingRect.origin.x, -croppingRect.origin.y);
    [self.view.layer renderInContext:ctx];

   // Retrieve a UIImage from the current image context:
   UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();

    // Return the image in a UIImageView:
   return snapshotImage;

}

Другие вопросы по тегам