cocoa - Resize NSImage in custom NSTextFieldCell -
i created drag , drop app using apple's example: https://developer.apple.com/library/mac/samplecode/sourceview/introduction/intro.html
i load actual image of dragged file.
when drag example image file nsoutlineview, see resized in way:
i used without modifications apple's imageandtextcell class custom nstextfieldcell.
how can resize image fit proportionally cell rect?
works perfect.
@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