2015-04-23 51 views
1

我創造了阻力和使用蘋果的例子下降應用:https://developer.apple.com/library/mac/samplecode/SourceView/Introduction/Intro.html調整大小NSImage中定製NSTextFieldCell

我拖着加載文件的實際圖像。

當我拖累例如該enter image description here圖像文件到我NSOutlineView,我看到它以這種方式調整:

enter image description here

我作爲是沒有任何修改蘋果的ImageAndTextCell類自定義NSTextFieldCell。

我如何調整此圖像以適合比例單元矩形?

+1

請檢查此鏈接:http://theocacao.com/document.page/498 –

+0

我試了一下,但是當我修改方法 - (無效)drawWithFrame:(的NSRect)cellFrame inView:(*的NSView)在ImageAndTextCell.m類中的controlView到NSImage * resizedImage = [self.myImage imageByScalingProportionallyToSize:....我有相同的結果,沒有任何更改.. – KAMIKAZE

+0

基於單元格的表已棄用。我建議你製作基於表格的視圖,然後你可以在每行/列中繪製任何你喜歡的東西。 –

回答

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