首页 文章

在自定义NSTextFieldCell中调整NSImage的大小

提问于
浏览
1

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

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

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

enter image description here

我没有任何修改Apple的 ImageAndTextCell 类用于自定义NSTextFieldCell .

我如何调整此图像的大小以适合按比例缩小?

1 回答

  • 0

    工作完美 .

    @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
    

相关问题