如何在iPhone中以编程方式保存带有时间戳的屏幕截图?

时间:2012-10-17 11:55:41

标签: ios datetime screenshot

您好我正在开发一款iPad应用程序,该应用程序需要自动截取屏幕截图,并且图像应以屏幕名称的名称保存,并保存在设备中的当前日期和当前时间。有人帮我这么做。

我已经尝试了以下代码。在该代码中截取屏幕截图,我将在该视图中的标签中打印名称。但是在标签时间不准确,所以我想将图像保存在时间附加的屏幕名称名称中。

        //-- Screen Capture --------------------------------------------------------------------//

UIImage *image = nil;

UIGraphicsBeginImageContext(loginBgImgVw.frame.size);

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MM-dd-yyyy HH:MM:SS"];
[formatter setTimeZone:[NSTimeZone localTimeZone]];

NSString *dateToday = [formatter stringFromDate:[NSDate date]];

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 600, 44)];
[label setText:dateToday];
NSString *fileNameStr = [NSString stringWithFormat:@"%@_Login_%@",providerIdStr,dateToday];

[label setText:fileNameStr];
label.backgroundColor = [UIColor clearColor];
[loginBgImgVw addSubview:label];
[formatter release];


[loginBgImgVw.layer renderInContext: UIGraphicsGetCurrentContext()];     
image = UIGraphicsGetImageFromCurrentImageContext();        
UIGraphicsEndImageContext();        

//=--

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docspath = [paths objectAtIndex:0];
NSLog(@"path=--%@",paths);

NSString *dataPath = [docspath stringByAppendingPathComponent:[NSString stringWithFormat:@"ProviderID_%@",providerIdStr]];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
}

NSString *savedImagePath = [dataPath stringByAppendingPathComponent:@"Login_Provider.png"];
NSData *imageData = UIImageJPEGRepresentation(image, 0.2);
[imageData writeToFile:savedImagePath atomically:NO];

UIImageWriteToSavedPhotosAlbum(image,self,@selector(image:didFinishSavingWithError:contextInfo:),NULL);

//--------------------------------------------------------------------------------------//

1 个答案:

答案 0 :(得分:2)

您需要将日期格式化程序更改为

[formatter setDateFormat:@"MM-dd-yyyy HH:mm:ss"];

MM代表月份,mm代表分钟。