• iOS AnchorPoint 引起的坐标问题


       这里主要讨论设置AnchorPoint 改变时,会影响我们预期的布局问题;

    一、初始代码布局

        //参照页面

        UIView *aView = [[UIView alloc]initWithFrame:CGRectMake(50, 50, 100, 100)];

        aView.backgroundColor = [UIColor redColor];

        [self.view addSubview:aView];

        

        UIView *bView = [[UIView alloc]initWithFrame:CGRectMake(150, 50, 100, 100)];

        bView.backgroundColor = [UIColor blueColor];

        [self.view addSubview:bView];

    运行效果如下(默认anchorPoint(0.5,0.5))

    其中 B 坐标信息 :  

     frame : (origin = (x = 150, y = 50), size = (width = 100, height = 100))

     center :(x = 200, y = 100)

    二、更改B页面 anchorPoint为 (0,0.5)

        bView.layer.anchorPoint = CGPointMake(0.0, 0.5);

    运行,结果如下:

    B 坐标信息如下

    frame   : (origin = (x = 200, y = 50), size = (width = 100, height = 100))

     center : (x = 200, y = 100)

    和“一 ”中结果 相比发现,center不变, x坐标向右移动了50pt;

    三、更改B页面 anchorPoint为 (0.0,0.0)

        bView.layer.anchorPoint = CGPointMake(0.0, 0.0);

    运行,结果如下:

    B 坐标信息如下

    frame   : (origin = (x = 200, y = 100), size = (width = 100, height = 100))

     center : (x = 200, y = 100)

    此时发现 origin 和center重叠了

    四、结论

        我们设置anchorPoint 时已经改变了我们的布局,这不是我们所期望的;

         从二、三运行结果可以发现一下结论:

    • center坐标的值都未改变。
    • center 点即使我们的锚点
    • 我们改变锚点值时,页面会相对于原中心点进行相应改变

    五、解决方案

         那么我们如何想要得到:只设定anchorPoint值,而不影响页面布局呢? 答案是,重新计算frame值;

        代码如下:

    /**
     设置锚点,且不影响之前的预期布局
    
     @param anchorPoint 锚点值如:{1,0.5}
     @param view 要更改的view
     */
    - (void)setViewAnchorPoint:(CGPoint)anchorPoint forView:(UIView*)view {
        CGPoint originAnchorPoint = view.layer.anchorPoint;
        CGPoint offetPoint = CGPointMake(anchorPoint.x - originAnchorPoint.x, anchorPoint.y - originAnchorPoint.y);
        CGFloat offetX =  (offetPoint.x)*view.frame.size.width;
        CGFloat offetY =  (offetPoint.y)*view.frame.size.height;
        view.layer.anchorPoint = anchorPoint;//设置这个值 说明已经改变了便宜量
        view.layer.position = CGPointMake(view.layer.position.x + offetX, view.layer.position.y + offetY);//将指定的偏宜量更改回来
    }

    那么我们设置需要更改的B页面如下调用即可:

        UIView *bView = [[UIView alloc]initWithFrame:CGRectMake(150, 50, 100, 100)];
        _bView = bView;
        bView.backgroundColor = [UIColor blueColor];
        [self setViewAnchorPoint:CGPointMake(1, 1) forView:bView];//只是测试多次连续设置结果
        [self setViewAnchorPoint:CGPointMake(0, 0.5) forView:bView];
        [self.view addSubview:bView];
        

    完美结局 

  • 相关阅读:
    git常用命令大全
    谷粒商城遇到的问题
    谷粒商城Seata(四十一)
    通过VMware Horizon Client访问虚拟机
    Qt 让窗口(或控件)居中
    QT 设置QDockWidget的初始大小
    Qt QDockWidget小结
    Qt QDockWidget停靠窗相关的信号
    Qt 基于Qt的词典开发系列--无边框窗口的缩放与拖动
    Qt 创建停靠悬浮窗口 QDockWidget
  • 原文地址:https://www.cnblogs.com/kingbo/p/7162364.html
Copyright © 2020-2023  润新知