【问题标题】:Image masking & create new UIImage图像遮罩和创建新的 UIImage
【发布时间】:2014-05-23 23:46:20
【问题描述】:

这是我面临的问题:

我已经使用 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)的帧的问题。

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

谢谢。

【问题讨论】:

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


【解决方案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;

}

【讨论】:

  • 您的答案看起来相同。您可能应该删除一个并保留另一个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-07
  • 2021-07-20
  • 2011-02-11
  • 1970-01-01
  • 2022-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多