Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
790 views
in Technique[技术] by (71.8m points)

iphone - Extract a part of UIImageView

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:

enter image description here

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:...]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...