您不能使用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