如何缩放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];

   这两段代码本人都亲自测试过,速度还挺快。

猜你喜欢

转载自blog.csdn.net/flame_007/article/details/84837939