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



我使用[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];
}

我认为这应该是对的。

    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];
    }

最新更新