Capture UIImage of UIView stuck in DrawRect method

2019-08-31 02:38发布

问题:

I am trying to capture image of my UIView but when I call this method

- (UIImage *) imageWithView:(UIView *)view
{
    UIGraphicsBeginImageContext(view.bounds.size);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return img;
}

my application enter in DrawRect method of my view and stuck in loop of these lines

[super drawRect:rect];
[curImage drawAtPoint:CGPointMake(0, 0)];
mid1 = midPoint(previousPoint1, previousPoint2);
mid2 = midPoint(currentPoint, previousPoint1);

context = UIGraphicsGetCurrentContext();

[self.layer renderInContext:context];

this is my drawRect Method

- (void)drawRect:(CGRect)rect
{

    [super drawRect:rect];
    [curImage drawAtPoint:CGPointMake(0, 0)];
    mid1 = midPoint(previousPoint1, previousPoint2);
    mid2 = midPoint(currentPoint, previousPoint1);

    context = UIGraphicsGetCurrentContext();

    [self.layer renderInContext:context];

    CGContextMoveToPoint(context, mid1.x, mid1.y);
    CGContextAddQuadCurveToPoint(context, previousPoint1.x, previousPoint1.y, mid2.x, mid2.y);

    CGContextSetLineCap(context, kCGLineCapRound);
    CGContextSetLineWidth(context, self.lineWidth);
    CGContextSetStrokeColorWithColor(context, self.lineColor.CGColor);

    CGContextStrokePath(context);
}

回答1:

For capturing UIView image simply run these lines & check:

    CGRect screenRect = [[UIScreen mainScreen] bounds];
    UIGraphicsBeginImageContextWithOptions(screenRect.size, NO, 0.0);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();


回答2:

you alse save image in docement directory and capturing UIView image

 UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *saveImage = UIGraphicsGetImageFromCurrentImageContext();
//inserttrue=TRUE;
UIGraphicsEndImageContext();
imagdata = UIImagePNGRepresentation(saveImage);
NSFileManager *fileMan = [NSFileManager defaultManager];
[self.view setContentStretch:CGRectMake(0, 0, 320, 480)];
NSString *fileName = [NSString stringWithFormat:@"%@.png",@"XYZ"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];

[fileMan createFileAtPath:pdfFileName contents:imagdata attributes:nil];