Reputation: 2731
I am using this code to render a UIView into an image
-(UIImage *)getImageForView:(UIView *)aView {
UIGraphicsBeginImageContextWithOptions(aView.bounds.size, NO, 0.0);
[aView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return viewImage;
}
The issue that I am having is that the view is not set out properly using autolayout. What should I do.
I currently create a UIView "viewA" with a frame which is the correct size for my view and then create my complicated intended view "ViewB" (which has auto layout on) and then add viewB as a subview to "viewA" then i give viewA to my above method.
First I thought viewA would not have to be added to some superview but it does not layout properly, should I be adding viewA with an alpha of 0 to a superview, then I assume maybe an "layoutIfNeeded" could be used but on which view should I do this?
Edit: Here is the code that creates the UIView
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 439)];
//This is the UIView that contains a lot of views
MyView *myView = [[MyView alloc] init];
myView.translatesAutoresizingMaskIntoConstraints = NO;
[view addSubview:myView];
[view addConstraints:[NSLayoutConstraint
constraintsWithVisualFormat:@"V:[myView(439)]"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(myView)]];
[view addConstraints:[NSLayoutConstraint
constraintsWithVisualFormat:@"H:[myView(320)]"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(myView)]];
What Worked for me in the end
[myView layoutIfNeeded];
[view layoutIfNeeded];
In other words calling it on both views.
Upvotes: 4
Views: 829
Reputation:
Send your view a layoutIfNeeded
message before rendering it in your image context.
Upvotes: 8