tags:

views:

452

answers:

2

How to draw a default image in imageview in the center of imageView?using - (void)drawRect:(NSRect)rect overridden method of NSImageView

+1  A: 

Why not just set the image view's image initially to the default image, then change it later?

Peter Hosey
Not a great solution if you want to have an image view display a "drop image here" graphic, for example. I'm sure you could do it by monitoring the image view's image and swapping in the custom graphic when the initial value is nil or the user deletes the current image, but it seems like less work just to add it in drawRect.
Marc Charbonneau
+2  A: 

Yes. That was one way. I've used the following code.

// Drawing 

   - (void)drawRect:(NSRect)rect
{
    if([self image])
    {  
     [[NSColor grayColor] set];
     NSRectFill(rect);

     //ImageView Bounds and Size
     NSRect vBounds = [self bounds];
     NSSize vSize = vBounds.size;

     //Get the size and origin of default image set to imageView
     NSRect imageRect;
     imageRect.size = [[self image] size];
     imageRect.origin = NSZeroPoint;

     //Create a preview image
     NSSize previewSize = NSMakeSize( [self image].width / 4.0, [self image].height / 4.0 );
     NSImage *previewImage = [[NSImage alloc] initWithSize:previewSize];


     //Get the point where the preview image needs to be draw
     NSRect newRect;
     newRect.origin.x = vSize.width/2-previewSize.width/2;
     newRect.origin.y = vSize.height/2-previewSize.height/2;
     newRect.size = [previewImage size];

     //Draw preview image in imageView
     [[self image] drawInRect:newRect fromRect:imageRect operation:NSCompositeSourceOver fraction:1.0];

     [previewImage release]; 
    }
}