Extract a part of UIImageView

和自甴很熟 提交于 2019-12-18 07:15:03

问题


I was wondering if it's possible to "extract" a part of UIImageView.

For example, I select using Warp Affine a part of the UIImageView and I know the selected part frame.

like in this image:

Is it possible to get from the original UIImageView only the selected part without losing quality?


回答1:


Get the snapshot of the view via category method:

@implementation UIView(Snapshot)

-(UIImage*)makeSnapshot
{
  CGRect wholeRect = self.bounds;

  UIGraphicsBeginImageContextWithOptions(wholeRect.size, YES, [UIScreen mainScreen].scale);

  CGContextRef ctx = UIGraphicsGetCurrentContext();
  [[UIColor blackColor] set];
  CGContextFillRect(ctx, wholeRect);
  [self.layer renderInContext:ctx];

  UIImage* image = UIGraphicsGetImageFromCurrentImageContext();

  UIGraphicsEndImageContext();

  return image;
}

@end

then crop it to your rect via another category method:

@implementation UIImage(Crop)

-(UIImage*)cropFromRect:(CGRect)fromRect
{
  fromRect = CGRectMake(fromRect.origin.x * self.scale,
                        fromRect.origin.y * self.scale,
                        fromRect.size.width * self.scale,
                        fromRect.size.height * self.scale);
  CGImageRef imageRef = CGImageCreateWithImageInRect(self.CGImage, fromRect);
  UIImage* crop = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];
  CGImageRelease(imageRef);
  return crop;
}

@end

in your VC:

UIImage* snapshot = [self.imageView makeSnapshot];
UIImage* imageYouNeed = [snapshot cropFromRect:selectedRect];

selectedRect should be in you self.imageView coordinate system, if no so then use selectedRect = [self.imageView convertRect:selectedRect fromView:...]




回答2:


Yes, it's possibile.First you should get the UIImageView's image, using this property:

@property(nonatomic, retain) UIImage *image;

And NSImage's :

@property(nonatomic, readonly) CGImageRef CGImage;

Then you get the cut image:

CGImageRef cutImage = CGImageCreateWithImageInRect(yourCGImageRef, CGRectMake(x, y, w, h));

If you want again a UIImage you should use this UIImage's method:

+ (UIImage *)imageWithCGImage:(CGImageRef)cgImage;

PS: I don't know how to do it directly, without convert it to CGImageRef, maybe there's a way.



来源:https://stackoverflow.com/questions/14042260/extract-a-part-of-uiimageview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!