开发者

Image and button in NSImageView are in wrong positions

开发者 https://www.devze.com 2023-03-10 09:10 出处:网络
I am assigning a button and an image to the same position (0, 0), but they are drawn in different locations. Why does this happen?

I am assigning a button and an image to the same position (0, 0), but they are drawn in different locations. Why does this happen?

Her开发者_JAVA百科e is my code:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification 
{

    // Insert code here to initialize your application 
    [window makeKeyWindow];
    [window setFrame:NSMakeRect(0, 0, 500, 468) display:YES];
    //[window setFrame:[[NSScreen mainScreen]frame] display:YES];
    [window setBackgroundColor:[NSColor clearColor]];
    [window center];
    [[window contentView] setAutoresizesSubviews:YES];

    NSImageView *subView = [[NSImageView alloc]initWithFrame:NSMakeRect(0, 0, 500, 468)];
    [subView setImage:[NSImage imageNamed:@"Flowers.jpg"]];
    [subView setAutoresizingMask:NSViewWidthSizable|NSViewHeightSizable];
    [subView setAutoresizesSubviews:YES];

    NSButton *subButton = [[NSButton alloc]initWithFrame:NSMakeRect(0, 0, 100, 40)];
    [subButton setTitle:@"testing"];
    [subButton setAutoresizingMask:NSViewWidthSizable|NSViewHeightSizable|NSViewMaxXMargin|NSViewMaxYMargin|NSViewMinXMargin|NSViewMinYMargin];
    [subView addSubview:subButton];
    [window setContentView:subView];
}

and here is the result after building:

Image and button in NSImageView are in wrong positions


The code is working exactly as you told it to; the button and the image view are in the correct position, both in the lower-left corner of the window.

The image does not fill the entire height of the image view because it has a different aspect ratio: It is significantly wider than it is tall, while the image view is nearly square.

There is no way to change the image view to work differently—to fill the image view even if it must crop the image to do so. The only options are to scale proportionally (preserving aspect ratio), scale regardless of ratio (fill the image view but possibly distort the image), and don't scale ever. If you want to scale proportionally to fill and crop, you will have to do it yourself. Alternatively, you may want to change the window's size to match the size—or at least the aspect ratio—of the image.

As an aside, it is unusual at best to put buttons inside image views in Cocoa. Most views—those that do something specific—should not contain other views. The button and the image view should each be inside a plain NSView.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号