我正在尝试显示一个简单的 NSImageView ,它的图像居中而不会像这样缩放:
就像iOS设置UIView的contentMode = UIViewContentModeCenter
一样所以我尝试了所有 NSImageScaling 值,这是我选择 NSScaleNone 时获得的
我真的不明白发生了什么: - /
答案 0 :(得分:5)
您可以手动生成正确大小和内容的图像,并将其设置为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;}
答案 1 :(得分:1)
这是NSImage的一个很棒的类别:NSImage+ContentMode
它允许iOS中的内容模式,效果很好。
答案 2 :(得分:1)
将图像缩放属性设置为NSImageScaleAxesIndependent,这将缩放图像以填充矩形。这不会保留纵横比。
答案 3 :(得分:0)
要获得所需的结果,图像展开以适合视图,您必须使用NSScaleToFit。这将改变照片的纵横比。
如果你想要等效的UIViewContentModeScaleAspectFill,图像的宽高比保持不变,图像会被放大以填充空间,并且它的溢出区域被修剪,然后查看这个人的NSImage类别:
http://rheard.com/blog/making-nsimages-resizable/
这可能就是你想要的。
答案 4 :(得分:0)
@Shagru的答案的快速版本(无提示)
func resizeImage(_ sourceImage:NSImage, size:CGSize) -> NSImage
{
let targetFrame = CGRect(origin: CGPoint.zero, size: size);
let targetImage = NSImage.init(size: size)
let sourceSize = sourceImage.size
let ratioH = size.height / sourceSize.height;
let ratioW = size.width / sourceSize.width;
var cropRect = CGRect.zero;
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.draw(in: targetFrame, from: cropRect, operation: .copy, fraction: 1.0, respectFlipped: true, hints: nil )
targetImage.unlockFocus()
return targetImage;
}