2

这是我面临的问题:

我已经使用 maskimage 实现了屏蔽。

这是原始图像:(尺寸:300width x 418height)

在此处输入图像描述

这是蒙版图像:(尺寸:165width x 215height)

在此处输入图像描述

下面是我用来根据蒙版裁剪图像并创建新的代码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();

它可以相应地工作并裁剪图像。结果如下:

在此处输入图像描述

但是最终裁剪图像(UIImage)图像的问题需要原始图像的帧(300x418)。

我不明白为什么会这样。我已经尝试了很多东西,但仍然没有解决方案。如果我做错了什么或缺少什么,任何人都可以建议我。

谢谢。

4

1 回答 1

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;

}

于 2014-05-10T19:09:56.853 回答