从UIVIEW + ipad截取屏幕截图

时间:2012-06-08 09:51:48

标签: iphone

我想拍摄viewcontroller的画面 我写了这个: -

- (UIImage *)captureScreenInRectWOScroll:(CGRect)captureFrame {    
    CALayer *layer;
    layer = self.view.layer;
    UIGraphicsBeginImageContext(captureFrame.size); 
    CGContextClipToRect (UIGraphicsGetCurrentContext(),captureFrame);
    [layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *screenImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return screenImage; 
}

我称之为这种方法的方式: -

UIImage *img_woscroll1 =[self captureScreenInRectWOScroll:CGRectMake(35,147,497,260)];

我想从下面的附图中截取地址的截图: - enter image description here

当我从上面的代码中获取hte截图时,我得到的图像顶部有很多空白区域(顶部是绿色图像),如果图像: -

enter image description here

请帮助我。如何从图像中获取适当的屏幕截图,这样我就不会在上方获得空白图像。

3 个答案:

答案 0 :(得分:3)

试试这个

UIGraphicsBeginImageContext(myView.frame.size);
[myView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *data=UIImagePNGRepresentation(viewImage);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *strPath = [documentsDirectory stringByAppendingPathComponent:@"myimage.png"];
[data writeToFile:strPath atomically:YES];

答案 1 :(得分:2)

试试这个: -

CGRect screenRect = CGRectMake(0, 90, 320,460);
UIGraphicsBeginImageContext(screenRect.size);

CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextFillRect(ctx, screenRect);

//you probably need an offset, adjust here
CGContextTranslateCTM(ctx, -20, -20);
[self.view.layer renderInContext:ctx];

UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

它可能对你有所帮助。谢谢:))

答案 2 :(得分:1)

试试这个。这可能会对你有帮助。

- (UIImage *)captureView:(UIView *)view {
CGRect screenRect = [[UIScreen mainScreen] bounds];

UIGraphicsBeginImageContext(screenRect.size);

CGContextRef ctx = UIGraphicsGetCurrentContext();
[[UIColor blackColor] set];
CGContextFillRect(ctx, screenRect);

[view.layer renderInContext:ctx];

UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

return newImage;

}