簡體   English   中英

捕獲陷在DrawRect方法中的UIView的UIImage

[英]Capture UIImage of UIView stuck in DrawRect method

我正在嘗試捕獲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();

您還將圖像保存在文檔目錄中並捕獲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];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM