9

次のようにスケーリングせずに、画像を中央に配置して単純なNSImageViewを表示しようとしています。

UIView の contentMode = **UIViewContentModeCenter** を設定したときに iOS が行うのと同じように

UIView の contentMode = UIViewContentModeCenterを設定したときに iOS が行うのと同じように

だから私はすべてのNSImageScaling値を試しました。これは、NSScaleNoneを選択したときに得られるものです

何が起こっているのか本当にわかりません:-/

何が起こっているのか本当にわかりません:-/

4

4 に答える 4

7

正しいサイズとコンテンツの画像を手動で生成し、それを 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;}
于 2013-08-05T17:16:36.000 に答える
4

NSImage のすばらしいカテゴリは次のとおりです: NSImage+ContentMode

iOS のようなコンテンツ モードが可能で、うまく機能します。

于 2015-12-22T13:28:03.850 に答える
2

画像スケーリング プロパティを NSImageScaleAxesIndependently に設定します。これにより、画像が四角形を埋めるようにスケーリングされます。これにより、縦横比が保持されません。

于 2016-09-13T07:32:17.393 に答える