任何代码都可以替换" imageWithSize"在Xcode上?

时间:2014-06-05 12:59:47

标签: objective-c macos nsimage cgimage

我使用[NSImage imageWithSize:方法将 NSPDFImageRep 绘制到图像上。但是 imageWithSize 方法只能在mac os x 10.8或更高版本上使用。有没有办法替换这种方法并用于10.6和10.7?可以使用CGImage吗?

代码:

NSString* localDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
NSString* pdfPath = [localDocuments stringByAppendingPathComponent:@"1.pdf"];
NSData* pdfData = [NSData dataWithContentsOfFile:pdfPath];
NSPDFImageRep* pdfImageRep = [NSPDFImageRep imageRepWithData:pdfData];
CGFloat factor = 300/72;
NSInteger pageCount = [pdfImageRep pageCount];
for(int i = 0 ; i < pageCount ; i++)
{
    [pdfImageRep setCurrentPage:i];
    NSImage* scaledImage = [NSImage imageWithSize:pdfImageRep.size flipped:NO drawingHandler:^BOOL(NSRect dstRect) {
        [pdfImageRep drawInRect:dstRect];
        return YES;
    }];
    NSImageRep* scaledImageRep = [[scaledImage representations] firstObject];
    /*
     * The sizes of the PDF Image Rep and the [NSImage  imageWithSize: drawingHandler:]-context
     * are define in terms of points.
     * By explicitly setting the size of the scaled representation in in Pixels, you 
     * define the relation between ponts & pixels.
     */
    scaledImageRep.pixelsWide = pdfImageRep.size.width * factor;
    scaledImageRep.pixelsHigh = pdfImageRep.size.height * factor;
    NSBitmapImageRep* pngImageRep = [NSBitmapImageRep imageRepWithData:[scaledImage TIFFRepresentation]];
    NSData* finalData = [pngImageRep representationUsingType:NSJPEGFileType properties:nil];
    NSString* pageName = [NSString stringWithFormat:@"Page_%ld.jpg", (long)[pdfImageRep currentPage]];
    [[NSFileManager defaultManager] createFileAtPath:[NSString stringWithFormat:@"%@%@", pdfPath, pageName] contents:finalData attributes:nil];
}

1 个答案:

答案 0 :(得分:2)

我认为这应该是正确的。

    NSImage* scaledImage;
    if ([NSImage respondsToSelector:@selector(imageWithSize:flipped:drawingHandler:)]) { //Check if the os supports it
         scaledImage = [NSImage imageWithSize:pdfImageRep.size flipped:NO drawingHandler:^BOOL(NSRect dstRect) {
              [pdfImageRep drawInRect:dstRect];
              return YES;
         }];

    } else { //use old drawing method
         scaledImage = [[[NSImage alloc] initWithSize:pdfImageRep.size] autorelease];
         [scaledImage lockFocus];
         [pdfImageRep drawInRect:dstRect];
         [scaledImage unlockFocus];
    }