将完整的UIImageView渲染为位图图像

我知道如何呈现一个普通的UIView到一个位图图像:

UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0.0); [view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *bitmapImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); 

问题是,如果view是一个带有从resizableImageWithCapInsets:返回的可伸缩的可resize的图像的UIImageView ,则通过这种方式得到的bitmapImage是原始图像 – 未拉伸的图像 – 而不是真正显示的拉伸图像。 我可以很容易地告诉,由bitmapImageview之间的大小差异。 所以我的问题是如何呈现一个UIImageView的图像是一个拉伸的可resize的图像显示的完整内容?

所以,我试了这段代码:

 UIEdgeInsets edgeInsets = UIEdgeInsetsMake(-20, -20, -20, -20); UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)]; imageView.image = [[UIImage imageNamed:@"number1.png"] resizableImageWithCapInsets:edgeInsets]; [self.view addSubview:imageView]; UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 0.0); [imageView.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *bmImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); NSArray *documentsPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [documentsPaths objectAtIndex:0]; [UIImagePNGRepresentation(bmImage) writeToFile:[documentsDir stringByAppendingString:@"num1.png"] atomically:YES]; 

得到这个:

在这里输入图像说明

并从此:

在这里输入图像说明

所以它看起来像代码工作,因为它应该。

我是个白痴! 代码是完美的工作。 我只是把别的东西搞乱了。 愚蠢的是,我把我的UIView类别的方法中的代码,但我命名的方法image 。 它适用于普通的UIView ,但是由于UIImageView有自己的image方法,而UIImageViewUIView的子类,所以当我尝试获取位图图像时会调用UIImageViewimage方法。