gpt4 book ai didi

cocoa - 对 NSImageView 缩放感到困惑

转载 作者:行者123 更新时间:2023-12-03 16:06:27 26 4
gpt4 key购买 nike

我正在尝试显示一个简单的 NSImageView ,其图像居中,而不像这样缩放:

Just like iOS does when you set an UIView's contentMode = **UIViewContentModeCenter**

就像 iOS 所做的那样,当您设置 UIView 的 contentMode = UIViewContentModeCenter

所以我尝试了所有NSImageScaling值,这就是我选择NSScaleNone时得到的结果

I really don't understand what's going on :-/

我真的不明白发生了什么:-/

最佳答案

您可以手动生成正确大小和内容的图像,并将其设置为 NSImageView 的图像,这样 NSImageView 不需要做任何事情。

NSImage *newImg = [self resizeImage:sourceImage size:newSize];
[aNSImageView setImage:newImg];

以下函数调整图像大小以适应新尺寸,同时保持纵横比不变。如果图像小于新尺寸,则会放大图像并填充新框架。如果图像大于新尺寸,则会缩小尺寸,并填充新框架

- (NSImage*) resizeImage:(NSImage*)sourceImage size:(NSSize)size{

NSRect targetFrame = NSMakeRect(0, 0, size.width, size.height);
NSImage* targetImage = [[NSImage alloc] initWithSize:size];

NSSize sourceSize = [sourceImage size];

float ratioH = size.height/ sourceSize.height;
float ratioW = size.width / sourceSize.width;

NSRect cropRect = NSZeroRect;
if (ratioH >= ratioW) {
cropRect.size.width = floor (size.width / ratioH);
cropRect.size.height = sourceSize.height;
} else {
cropRect.size.width = sourceSize.width;
cropRect.size.height = floor(size.height / ratioW);
}

cropRect.origin.x = floor( (sourceSize.width - cropRect.size.width)/2 );
cropRect.origin.y = floor( (sourceSize.height - cropRect.size.height)/2 );



[targetImage lockFocus];

[sourceImage drawInRect:targetFrame
fromRect:cropRect //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;}

关于cocoa - 对 NSImageView 缩放感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13750234/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com