Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align a subview to the center of a parent NSView

Tags:

macos

cocoa

I'm developing a program in which I am programmatically adding an NSImageView to a custom NSView class. While creating the image-view, I am passing the frame of the parent container.

-(NSImageView *)loadNSImage:(NSString *)imageName frame:(NSRect)frame{
    imageName = [[NSBundle mainBundle] pathForResource:imageName ofType:@"png"];
    NSImage *image = [[NSImage alloc] initWithContentsOfFile:imageName]; 
    NSImageView *imageView = [[NSImageView alloc]initWithFrame:frame];
    [imageView setImage:image];
    [imageView setImageScaling:NSImageScaleProportionallyUpOrDown];
    [imageView setAutoresizingMask:NSViewHeightSizable | NSViewWidthSizable | NSViewMaxXMargin | NSViewMaxYMargin | NSViewMinXMargin | NSViewMinYMargin];
    [imageView setImageAlignment:NSImageAlignCenter];
    [image release];
    return imageView;
}

Then I am using the addSubView method to add this into the Custom View. The problem is that the image sticks to the bottom-left of the parent view. How can I place this image in the center of the parent view?

I have tried adding an offset to the frame origin, but that doesn't really work when the window is resized, or if an image with a different size is loaded.

Any help would be appreciated.

like image 544
Akshay Avatar asked Jan 13 '11 14:01

Akshay


1 Answers

I'm not sure if this is the best way to do it, but I just do simple math when I want to center a subview inside its parent.

You need to set all the margins to be auto-resizable if you want it to stay centered.

[subview setFrameOrigin:NSMakePoint(
  round((NSWidth([parentView bounds]) - NSWidth([subview frame])) / 2),
  round((NSHeight([parentView bounds]) - NSHeight([subview frame])) / 2)
)];
[subview setAutoresizingMask:NSViewMinXMargin | NSViewMaxXMargin | NSViewMinYMargin | NSViewMaxYMargin];

This is just calculating the margins required to get a centered origin.

If you need the centered frame before you invoke initWithFrame: then just use the above logic to compute the frame origin values.

like image 171
d11wtq Avatar answered Oct 12 '22 03:10

d11wtq