如何縮放NSImage, 減少圖片的大小?

可以利用drawInRect函數來實現,下面列舉兩個例子進行介紹:

一、利用 NSImageRep 的 drawInRect 函數,代碼如下:

    NSImage* sourceImage = ...;

    NSSize size = ...;

    NSRect targetFrame = NSMakeRect(0, 0, size.width, size.height);     

    NSImage* targetImage = nil;

    NSImageRep *sourceImageRep =

    [sourceImage bestRepresentationForRect:targetFrame

                                   context:nil

                                     hints:nil];

 

    targetImage = [[NSImage alloc] initWithSize:size];

    [targetImage lockFocus];

    [sourceImageRep drawInRect: targetFrame];

    [targetImage unlockFocus];

 

二、利用 NSImage( NSImageRep 也一樣)的稍微複雜一點的函數,可以設置的更詳細一點:

代碼如下:

    NSImage* sourceImage = ...;

    NSSize size = ...;

    NSRect targetFrame = NSMakeRect(0, 0, size.width, size.height);

    NSImage*  targetImage = [[NSImage alloc] initWithSize:size];

    [targetImage lockFocus];

    [sourceImage drawInRect:targetFrame

                   fromRect:NSZeroRect       //portion of source image to draw

                  operation:NSCompositeCopy  //compositing operation

                   fraction:1.0              //alpha (transparency) value

             respectFlipped:YES              //coordinate system

                      hints:@{NSImageHintInterpolation:

     [NSNumber numberWithInt:NSImageInterpolationLow]}];

    [targetImage unlockFocus];

 

   這兩段代碼本人都親自測試過,速度還挺快。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章