【问题标题】:Extract a part of UIImageView提取部分 UIImageView
【发布时间】:2012-12-26 14:54:34
【问题描述】:

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

例如,我使用 Warp Affine 选择了 UIImageView 的一部分,并且我知道所选部分 frame

喜欢这张图片:

是否可以从原始UIImageView 中仅获取选定的部分而不损失质量?

【问题讨论】:

  • 你是怎么做这个选择区域的? =)

标签: iphone objective-c uiimageview resize warp


【解决方案1】:

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

@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

然后通过另一种类别方法将其裁剪到您的矩形:

@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

在你的 VC 中:

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

selectedRect 应该在你的self.imageView 坐标系中,如果没有,那么使用 selectedRect = [self.imageView convertRect:selectedRect fromView:...]

【讨论】:

  • 很抱歉,您的图像裁剪方法效果不佳。它似乎返回图像的随机部分,而不是选定的部分。我目前正在使用这种方法:pastie.org/private/wxmefesfdsu30vxf8un7q 它似乎工作得很好,但它有点不准确,也许你可以帮我解决它?例如,如果我拍摄了 iPhone 屏幕,然后全选,它会返回所有选定的 iPhone 屏幕,而没有状态栏。
  • 哦,后者不是UIImageView的方法,而是UIImage类的方法。首先需要获取 UIImageView 的快照,然后用后一种方法裁剪快照。
  • 伙计,我再次尝试了你所说的方法,现在它像我发布的那样“运行良好”。但它仍然不准确,它不像我的那样 100% 完美。我可以做一个小视频给你看吗?非常感谢。
  • 查看编辑。您选择的矩形在哪个坐标系中?
【解决方案2】:

是的,这是可能的。首先你应该得到 UIImageView 的图像,使用这个属性:

@property(nonatomic, retain) UIImage *image;

还有 NSImage 的:

@property(nonatomic, readonly) CGImageRef CGImage;

然后你得到剪切图像:

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

如果你想要一个 UIImage,你应该使用这个 UIImage 的方法:

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

PS:不知道怎么直接做,不用转成CGImageRef,或许有办法。

【讨论】:

  • 显示你尝试过的东西,x,y,w,h 只是象征性的,你使用的是什么坐标,视图坐标是什么?
  • UIImageView 坐标为:20,8,280,400。 UIImageView 坐标的选定部分为:31,255.5,262,142。
  • 你要越界了,原点是(20,8),其他点是宽度/高度。例如,如果你想要图像的下半部分,你可以写 x=220 ,y=300, w=60, h=100。如果这不采用确切的坐标,请尝试稍微更改矩形坐标和大小。顺便说一句,我不确定 UIImage 是否相同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-02
  • 2013-02-12
  • 2020-10-08
相关资源
最近更新 更多