Render a full UIImageView to a bitmap image

余生颓废 提交于 2020-01-02 09:57:27

问题


I know how to render a normal UIView to a bitmap image:

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

The problem is that if view is a UIImageView with a stretched resizable image returned from resizableImageWithCapInsets:, bitmapImage gotten this way is the original image — the un-stretched one — instead of the really displayed stretched image. I can easily tell that by the size difference between bitmapImage and view. So my question is how to render the full content displayed by a UIImageView whose image is a stretched resizable image?


回答1:


So, I tried this piece of code:

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];

and got this:

and from this:

So it seems like the code works as it is supposed to.




回答2:


I'm an idiot! The code is perfectly working. I just messed up something somewhere else. The stupid thing is that I put the code in a method of my UIView category but I named the method image. It works perfectly for general UIViews, but as UIImageView has its own image method and UIImageView is a subclass of UIView, UIImageView's image method is called when I tried to get my bitmap image.



来源:https://stackoverflow.com/questions/8788376/render-a-full-uiimageview-to-a-bitmap-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!