您不能使用NSImage的size
屬性,因爲它只與圖像表示的像素尺寸有間接關係。以調整像素尺寸的一個好方法是使用NSImageRep的drawInRect
方法:
- (BOOL)drawInRect:(NSRect)rect
繪製整個圖像中指定的矩形,根據需要,以適應縮放它。
這裏是一個圖像調整大小的方法(創建一個新的NSImage在你想要的像素大小)。
- (NSImage*) resizeImage:(NSImage*)sourceImage size:(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];
return targetImage;
}
這是從一個更詳細的解答我給這裏:NSImage doesn't scale
另一種工作調整大小的方法是NSImage中方法drawInRect:fromRect:operation:fraction:respectFlipped:hints
- (void)drawInRect:(NSRect)dstSpacePortionRect
fromRect:(NSRect)srcSpacePortionRect
operation:(NSCompositingOperation)op
fraction:(CGFloat)requestedAlpha
respectFlipped:(BOOL)respectContextIsFlipped
hints:(NSDictionary *)hints
這種方法的主要優點是hints
的NSDictionary,在這裏你可以控制插值。放大圖像時,這會產生廣泛的不同結果。 NSImageHintInterpolation
是一個枚舉,可以採取五個值之一...
enum {
NSImageInterpolationDefault = 0,
NSImageInterpolationNone = 1,
NSImageInterpolationLow = 2,
NSImageInterpolationMedium = 4,
NSImageInterpolationHigh = 3
};
typedef NSUInteger NSImageInterpolation;
使用這種方法,沒有必要提取imageRep的中間步驟,將NSImage中做正確的事...
- (NSImage*) resizeImage:(NSImage*)sourceImage size:(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];
return targetImage;
}
感謝這正是我需要的! – atomikpanda 2013-03-23 20:54:54
這個答案對我來說很重要。 :) 非常感謝! – 2013-09-07 19:48:54