如何调整NSImage的大小? [英] How to resize NSImage?
问题描述
我有一个NSBitmapImageRep
,大小为W
x H
.
I have an NSBitmapImageRep
which is W
xH
size.
我创建NSImage
并调用addRepresentation:
.然后我需要调整NSImage
的大小.
I create NSImage
and call addRepresentation:
. Then I need to resize the NSImage
.
我尝试了setSize
方法,但是它不起作用.我该怎么办?
I tried setSize
method but it doesn't work. What should I do?
推荐答案
由于此答案仍然是公认的答案,但在编写时并未考虑视网膜屏幕,因此,我将直接在该线程下方直接指向一个更好的解决方案的链接: Swift 4
Since this answer is still the accepted answer, but was written without Retina screens in mind, I will straight up link to a better solution further down the thread: Objective-C Swift 4
因为Paresh的方法是完全正确的,但自10.8开始已弃用,因此我将在下面发布10.8的工作代码.不过,所有功劳都归功于Paresh的答案.
Because the method of Paresh is totally correct but deprecated since 10.8 I'll post the working 10.8 code below. All credit to Paresh's answer though.
- (NSImage *)imageResize:(NSImage*)anImage newSize:(NSSize)newSize {
NSImage *sourceImage = anImage;
[sourceImage setScalesWhenResized:YES];
// Report an error if the source isn't a valid image
if (![sourceImage isValid]){
NSLog(@"Invalid Image");
} else {
NSImage *smallImage = [[NSImage alloc] initWithSize: newSize];
[smallImage lockFocus];
[sourceImage setSize: newSize];
[[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
[sourceImage drawAtPoint:NSZeroPoint fromRect:CGRectMake(0, 0, newSize.width, newSize.height) operation:NSCompositeCopy fraction:1.0];
[smallImage unlockFocus];
return smallImage;
}
return nil;
}
这篇关于如何调整NSImage的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!