我正在开发一个程序,我在其中以编程方式将NSImageView添加到自定义NSView类.在创建图像视图时,我传递父容器的框架.
-(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;
}
Run Code Online (Sandbox Code Playgroud)
然后我使用该addSubView方法将其添加到自定义视图中.问题是图像粘在父视图的左下角.如何将此图像放在父视图的中心?
我已经尝试在帧原点上添加一个偏移量,但是当调整窗口大小时,或者加载了不同大小的图像时,这实际上并不起作用.
任何帮助,将不胜感激.
d11*_*wtq 40
我不确定这是否是最好的方法,但是当我想将子视图置于其父级中心时,我只是做简单的数学运算.
如果希望它保持居中,则需要将所有边距设置为可自动调整大小.
[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];
Run Code Online (Sandbox Code Playgroud)
这只是计算获得居中原点所需的边距.
如果在调用之前需要居中框架,initWithFrame:则只需使用上述逻辑来计算框架原点值.
| 归档时间: |
|
| 查看次数: |
12722 次 |
| 最近记录: |