图像掩蔽&创建新的UIImage

时间:2014-04-10 10:18:46

标签: ios objective-c uiimageview uiimage image-masking

以下是我面临的问题:

我已经使用maskimage实现了遮罩。

这是原始图像:(尺寸:300宽x 418高)

enter image description here

这是面具图像:(尺寸:165宽x 215高)

enter image description here

下面是我根据面具& amp;创建新的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();

它适用于&因此庄稼形象。结果如下:

enter image description here

但问题是最终的croppedImage(UIImage)图像采用了原始图像的帧(300x418)。

我不知道为什么会这样。我尝试了很多东西,但仍然没有解决方案。如果我做错了什么或者遗漏了什么,请任何人建议我。

感谢。

1 个答案:

答案 0 :(得分: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;

}