提取UIImageView的一部分 [英] Extract a part of UIImageView

查看:168
本文介绍了提取UIImageView的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以提取 UIImageView 的一部分。

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

例如,我选择使用Warp Affine作为 UIImageView 的一部分,我知道所选部分 frame

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

如下图所示:

是否可以从原始 UIImageView获取只有选定的部分没有丢失质量?

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

推荐答案

通过类别方法获取视图的快照:

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

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

selectedRect 应该在你身边 self.imageView 坐标系,如果没有则使用
selectedRect = [self.imageView convertRect:selectedRect fromView:...]

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

这篇关于提取UIImageView的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆