UIBezierPath : Incorrect retrieval of view screen

2019-06-06 07:41发布

问题:

I'm taking the screenshot following way.

- (UIImage*)screenshot 
{
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    CGRect rect = [keyWindow bounds];
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [keyWindow.layer renderInContext:context];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

On UIView I'm drawing paths using UIBezierPath.

The screenshots that I'm getting are incorrect like this

Any ideas why the upper part is cut to blank ? On UIView all drawing is displayed correctly.


UPDATE : This happens when I draw a long path with UIBezierPath when I release the my brush and get the screenshot it gets the screenshot correctly.

回答1:

I saw the another thread which you post. According to the apple technical Q&A, you need to adjust the geometry coordinate first. So, before render the layer of window, do following things first.

// -renderInContext: renders in the coordinate space of the layer,
// so we must first apply the layer's geometry to the graphics context
CGContextSaveGState(context);
// Center the context around the window's anchor point
CGContextTranslateCTM(context, [window center].x, [window center].y);
// Apply the window's transform about the anchor point
CGContextConcatCTM(context, [window transform]);
// Offset by the portion of the bounds left of and above the anchor point
CGContextTranslateCTM(context,
                      -[window bounds].size.width * [[window layer] anchorPoint].x,
                      -[window bounds].size.height * [[window layer] anchorPoint].y);


回答2:

- (UIImage*)screenshot :(UIView*)vw
{

    CGRect rect = [vw bounds];
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [vw.layer renderInContext:context];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

Use This one



回答3:

-(IBAction)takeScreenShot:(id)sender
{

    UIGraphicsBeginImageContext(self.view.bounds.size); 

    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; 

    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);
}