次のようにスケーリングせずに、画像を中央に配置して単純なNSImageViewを表示しようとしています。
UIView の contentMode = UIViewContentModeCenterを設定したときに iOS が行うのと同じように
だから私はすべてのNSImageScaling値を試しました。これは、NSScaleNoneを選択したときに得られるものです
何が起こっているのか本当にわかりません:-/
次のようにスケーリングせずに、画像を中央に配置して単純なNSImageViewを表示しようとしています。
UIView の contentMode = UIViewContentModeCenterを設定したときに iOS が行うのと同じように
だから私はすべてのNSImageScaling値を試しました。これは、NSScaleNoneを選択したときに得られるものです
何が起こっているのか本当にわかりません:-/
正しいサイズとコンテンツの画像を手動で生成し、それを 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;}
NSImage のすばらしいカテゴリは次のとおりです: NSImage+ContentMode
iOS のようなコンテンツ モードが可能で、うまく機能します。
画像スケーリング プロパティを NSImageScaleAxesIndependently に設定します。これにより、画像が四角形を埋めるようにスケーリングされます。これにより、縦横比が保持されません。