我将图像视图传递给需要图像视图大小的init方法。然后调用convertRect:toView:
- (id) initWithImageView:(UIImageView*) imageView {
self = [super init];
if (self) {
CGRect imageViewFrame = [[imageView superview] convertRect: imageView.frame toView: self.view];
}
}
以下是:
MyViewController *viewController = [[MyViewController alloc] initWithImageView:imageView];
viewController.delegate = self;
[self.tabBarController presentViewController:viewController animated:NO completion:nil];
然后imageViewFrame
(origin = (x = 0, y = -120.22867049625003), size = (width = 750, height = 750))
imageView的框架为
frame = (0 -60.1143; 375 375);
它的超级视图有一个框架
frame = (0 0; 375 254.5);
为什么要放大x2?
在iPhone 6 plus(3x)模拟器上进一步测试使imageViewFrame
(origin = (x = 0, y = -199.30952358000002), size = (width = 1242, height = 1242))
第一次测试是在iPhone 6模拟器(2x)上完成的。 为什么convertRect:toView:以像素而不是点工作?
答案 0 :(得分:2)
在-initWithImageView:
中,您的self.view
尚未生成,您可以尝试缓存imageView
临时,并在-viewDidLoad
中执行rect转换操作:
// If you don't user Interface Builder
- (void)loadView
{
CGRect frame = <your_view_frame>;
UIView * view = [[UIView alloc] initWithFrame:frame];
self.view = view;
}
- (void)viewDidLoad
{
[super viewDidLoad];
CGRect imageViewFrame = [[imageView superview] convertRect:imageView.frame toView:self.view];
...
}
正如文档所说的那样-convertRect:toView:
的观点:
作为转换操作目标的视图。如果view为nil,则此方法将转换为窗口基坐标。否则,视图和接收者都必须属于同一个UIWindow对象。
如果您坚持使用-initWithImageView
方法,请声明自定义视图iVar,alloc&amp;在-initWithImageView
方法中初始化,然后在-loadView
中,将iVar分配给self.view
。当然,您在-initWithImageView
中转换rect的方式应该是
CGRect frame = <your_view_frame>;
_iVarView = [[UIView alloc] initWithFrame:frame];
CGRect imageViewFrame = [[imageView superview] convertRect:imageView.frame
toView:_iVarView];
在-loadView
:
- (void)loadView
{
self.view = _iVarView;
}
但不建议以这种方式进行,我建议您使用正确的视图生命循环方法初始化UI。
答案 1 :(得分:1)
这是一个正确的方法: SWIFT:
extension UIView {
func convertRectCorrectly(rect: CGRect, toView view: UIView) -> CGRect {
if UIScreen.mainScreen().scale == 1 {
return self.convertRect(rect, toView: view)
}
else if self == view {
return rect
}
else {
var rectInParent = self.convertRect(rect, toView: self.superview)
rectInParent.origin.x /= UIScreen.mainScreen().scale
rectInParent.origin.y /= UIScreen.mainScreen().scale
let superViewRect = self.superview!.convertRectCorrectly(self.superview!.frame, toView: view)
rectInParent.origin.x += superViewRect.origin.x
rectInParent.origin.y += superViewRect.origin.y
return rectInParent
}
}
}