zoukankan      html  css  js  c++  java
  • 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];
        

    完美结局 

  • 相关阅读:
    Vue 介绍
    Django 组件-分页器
    Django 组件content_type
    DRF 解析器组件
    Django
    Django 组件-ModelForm
    Django 组件-用户认证
    Django 组件-中间件
    Django 组件-cookie与session
    Django CBV与FBV
  • 原文地址:https://www.cnblogs.com/kingbo/p/7162364.html
Copyright © 2011-2022 走看看