2017-02-21 2 views
0
- (void)takeScreenShot { 
    CGImageRef screenShot = CGWindowListCreateImage(CGRectInfinite, kCGWindowListOptionOnScreenOnly, kCGNullWindowID, kCGWindowImageDefault); 
    CGImageWriteToFile(screenShot, [@"~/code/screenshot.png" stringByExpandingTildeInPath]); 
} 

BOOL CGImageWriteToFile(CGImageRef image, NSString *path) { 
    CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:path]; 
    CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, kUTTypePNG, 1, NULL); 
    if (!destination) { 
     NSLog(@"Failed to create CGImageDestination for %@", path); 
     return NO; 
    } 

    CGImageDestinationAddImage(destination, image, nil); 

    if (!CGImageDestinationFinalize(destination)) { 
     NSLog(@"Failed to write image to %@", path); 
     CFRelease(destination); 
     return NO; 
    } 

    CFRelease(destination); 
    return YES; 
} 

Не удалось создать CGImageDestination для /Users/"username"/Library/Containers/"bundleidentifier"/Data/code/screenshot.pngКак написать CGImageRef в файл png. CGImageDestinationCreateWithURL возвращает ноль

Так пункт назначения не возвращается. Предпочтительно, я хотел бы написать ~/code/screenshot.png, но если это что-то с песочницей, также нормально писать в "песочницу"

Как написать скриншот файла, к которому я могу получить доступ позже ?

Я адаптировал код из Saving CGImageRef to a png file?

+2

Это не допустимый путь к папке, принадлежащей изолированному программному обеспечению. –

+0

Ах да. Изменение пути к @ "screenshot.png" позволяет успешно сохранить изображение. – user12345625

ответ

1
@import MobileCoreServices; // or `@import CoreServices;` on Mac 
@import ImageIO; 

BOOL CGImageWriteToFile(CGImageRef image, NSString *path) { 
    CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:path]; 
    CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, kUTTypePNG, 1, NULL); 
    if (!destination) { 
     NSLog(@"Failed to create CGImageDestination for %@", path); 
     return NO; 
    } 

    CGImageDestinationAddImage(destination, image, nil); 

    if (!CGImageDestinationFinalize(destination)) { 
     NSLog(@"Failed to write image to %@", path); 
     CFRelease(destination); 
     return NO; 
    } 

    CFRelease(destination); 
    return YES; 
} 

Вы должны добавить ImageIO и MobileCoreServices к вашему проекту, а также должны добавить заголовок.

+0

.. @ пользователь12345625 – sp309

Смежные вопросы