成功使用iOS 7中引入的UIView
新drawViewHierarchyInRect:afterScreenUpdates:
方法获取图像表示(通过UIGraphicsGetImageFromCurrentImageContext()
)以模糊我的应用程序还需要获取一部分视图。我设法以下列方式得到它:
UIImage *image;
CGSize blurredImageSize = [_blurImageView frame].size;
UIGraphicsBeginImageContextWithOptions(blurredImageSize, YES, .0f);
[aView drawViewHierarchyInRect: [aView bounds] afterScreenUpdates: YES];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
这可让我在aView
的框架后检索_blurImageView
的内容。
然而,现在,我需要获得aView
的一部分,但这次这部分将是“内部”。下面是一个代表我想要实现的目标的图像。
我已经尝试创建一个新的图形上下文并将其大小设置为部分的大小(红色框)并调用aView
来绘制代表红色框的框架的矩形(当然它的superview的框架是相同的至aView
's)但获得的图像全黑(空)。
答案 0 :(得分:3)
经过大量的调整后,我设法找到了能够完成这项工作的东西,但是我非常怀疑这是可行的方法。
这是我的[created-for-Stack Overflow]代码:
- (UIImage *) imageOfPortionOfABiggerView
{
UIView *bigViewToExtractFrom;
UIImage *image;
UIImage *wholeImage;
CGImageRef _image;
CGRect imageToExtractFrame;
CGFloat screenScale = [[UIScreen mainScreen] scale];
// have to scale the rect due to (I suppose) the screen's scale for Core Graphics.
imageToExtractFrame = CGRectApplyAffineTransform(imageToExtractFrame, CGAffineTransformMakeScale(screenScale, screenScale));
UIGraphicsBeginImageContextWithOptions([bigViewToExtractFrom bounds].size, YES, screenScale);
[bigViewToExtractFrom drawViewHierarchyInRect: [bigViewToExtractFrom bounds] afterScreenUpdates: NO];
wholeImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// obtain a CGImage[Ref] from another CGImage, this lets me specify the rect to extract.
// However since the image is from a UIView which are all at 2x scale (retina) if you specify a rect in points CGImage will not take the screen's scale into consideration and will process the rect in pixels. You'll end up with an image from the wrong rect and half the size.
_image = CGImageCreateWithImageInRect([wholeImage CGImage], imageToExtractFrame);
wholeImage = nil;
// have to specify the image's scale due to CGImage not taking the screen's scale into consideration.
image = [UIImage imageWithCGImage: _image scale: screenScale orientation: UIImageOrientationUp];
CGImageRelease(_image);
return image;
}
我希望这会帮助那些困扰我的问题的人。随意改进我的片段。
由于