How to resize NSImage?

前端 未结 10 1650
萌比男神i
萌比男神i 2020-12-02 21:21

I have an NSBitmapImageRep which is WxH size.

I create NSImage and call addRepresentation:. Then I n

10条回答
  •  时光取名叫无心
    2020-12-02 21:26

    Thomas Johannesmeyer's answer using lockFocus doesn't work as you may intend on Retina/HiDPI screens: it resizes to the desired points in the screen's native scale, not pixels.

    • If you're resizing for display on screen, use that method.
    • If you're resizing for a file with exact pixel dimensions, it'll be twice as large when running on Retina (2x DPI) screens.

    This method, cobbled together from various answers including some in this related question, resizes to the specified pixel dimensions regardless of current screen DPI:

    + (NSImage *)resizedImage:(NSImage *)sourceImage toPixelDimensions:(NSSize)newSize
    {
        if (! sourceImage.isValid) return nil;
    
        NSBitmapImageRep *rep = [[NSBitmapImageRep alloc]
                  initWithBitmapDataPlanes:NULL
                                pixelsWide:newSize.width
                                pixelsHigh:newSize.height
                             bitsPerSample:8
                           samplesPerPixel:4
                                  hasAlpha:YES
                                  isPlanar:NO
                            colorSpaceName:NSCalibratedRGBColorSpace
                               bytesPerRow:0
                              bitsPerPixel:0];
        rep.size = newSize;
    
        [NSGraphicsContext saveGraphicsState];
        [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithBitmapImageRep:rep]];
        [sourceImage drawInRect:NSMakeRect(0, 0, newSize.width, newSize.height) fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];
        [NSGraphicsContext restoreGraphicsState];
    
        NSImage *newImage = [[NSImage alloc] initWithSize:newSize];
        [newImage addRepresentation:rep];
        return newImage;
    }
    

提交回复
热议问题