gpt4 book ai didi

cocoa - 在自定义 NSTextFieldCell 中调整 NSImage 大小

转载 作者:行者123 更新时间:2023-12-03 17:20:37 25 4
gpt4 key购买 nike

我使用Apple的示例创建了拖放应用程序:https://developer.apple.com/library/mac/samplecode/SourceView/Introduction/Intro.html

我加载拖动文件的实际图像。

当我拖动例如这个 enter image description here 时图像文件到我的 NSOutlineView 中,我看到它以这种方式调整大小:

enter image description here

我按原样使用 Apple 的 ImageAndTextCell 类来自定义 NSTextFieldCell,无需任何修改。

如何调整该图像的大小以按比例适应单元格矩形?

最佳答案

工作完美。

@implementation NSImage (ProportionalScaling)

- (NSImage*)imageByScalingProportionallyToSize:(NSSize)targetSize
{
NSImage* sourceImage = self;
NSImage* newImage = nil;

if ([sourceImage isValid])
{
NSSize imageSize = [sourceImage size];
float width = imageSize.width;
float height = imageSize.height;

float targetWidth = targetSize.width;
float targetHeight = targetSize.height;

float scaleFactor = 0.0;
float scaledWidth = targetWidth;
float scaledHeight = targetHeight;

NSPoint thumbnailPoint = NSZeroPoint;

if ( NSEqualSizes( imageSize, targetSize ) == NO )
{

float widthFactor = targetWidth / width;
float heightFactor = targetHeight / height;

if ( widthFactor < heightFactor )
scaleFactor = widthFactor;
else
scaleFactor = heightFactor;

scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;

if ( widthFactor < heightFactor )
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;

else if ( widthFactor > heightFactor )
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
}

newImage = [[NSImage alloc] initWithSize:targetSize];

[newImage lockFocus];

NSRect thumbnailRect;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight;

[sourceImage drawInRect: thumbnailRect
fromRect: NSZeroRect
operation: NSCompositeSourceOver
fraction: 1.0];

[newImage unlockFocus];

}

return [newImage autorelease];
}

@end

关于cocoa - 在自定义 NSTextFieldCell 中调整 NSImage 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29817609/

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