lance
lance

Reputation:

How to draw a default image in imageview in the center of imageView?

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

Upvotes: 0

Views: 1764

Answers (2)

lance
lance

Reputation:

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]; 
    }
}

Upvotes: 3

Peter Hosey
Peter Hosey

Reputation: 96353

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

Upvotes: 1

Related Questions