【问题标题】:Resize NSImage in custom NSTextFieldCell在自定义 NSTextFieldCell 中调整 NSImage 的大小
【发布时间】:2015-04-23 08:19:41
【问题描述】:

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

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

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

我按原样使用 Apple 的 ImageAndTextCell 自定义 NSTextFieldCell 类。

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

【问题讨论】:

  • 请查看此链接:theocacao.com/document.page/498
  • 我试过了,但是当我修改方法时 - ImageAndTextCell.m 类中的 (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView 到 NSImage *resizedImage = [self.myImage imageByScalingProportionallyToSize: ....我有相同的结果,没有任何改变..
  • 不推荐使用基于单元格的表格。我建议您将表格视图设为基于视图,然后您可以在每一行/每列中绘制您喜欢的任何内容。
  • 您的意思是在我的 NSOutlineView 设置选项中 - 表视图:“基于视图”?目前我在那里有“基于细胞的”。
  • 是的,完全正确。这是弃用通知:developer.apple.com/library/mac/releasenotes/AppKit/RN-AppKit

标签: cocoa resize nsoutlineview nsimage nstextfieldcell


【解决方案1】:

完美运行。

@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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多