如何调整NSImage的大小? [英] How to resize NSImage?

查看:113
本文介绍了如何调整NSImage的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSBitmapImageRep,大小为W x H.

I have an NSBitmapImageRep which is WxH 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆