捕获UIView的UIImage卡在DrawRect方法中
我想捕捉我的UIView的图像,但是当我调用这个方法
- (UIImage *) imageWithView:(UIView *)view { UIGraphicsBeginImageContext(view.bounds.size); [view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage * img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return img; }
我的应用程序进入我的视图的DrawRect方法,并卡在这些行的循环
[super drawRect:rect]; [curImage drawAtPoint:CGPointMake(0, 0)]; mid1 = midPoint(previousPoint1, previousPoint2); mid2 = midPoint(currentPoint, previousPoint1); context = UIGraphicsGetCurrentContext(); [self.layer renderInContext:context];
这是我的drawRect
方法
- (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); }
为了捕获UIView图像,只需运行这些行并检查:
CGRect screenRect = [[UIScreen mainScreen] bounds]; UIGraphicsBeginImageContextWithOptions(screenRect.size, NO, 0.0); [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
您也可以将图像保存在docement目录中并捕获UIView图像
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];