如何以像素为单位获取视图之间的距离?

 人马上山_237 发布于 2023-02-13 16:03

如下图所示.我有一个relative layout.我有我ImageView的相同,我需要在视图开始和这个ImageView之间获得像素差距.我的活动如下.请指教.我试过各种各样的方法,topY()但找不到解决办法.

在pixcel找到距离

    

            
        

    

    


Douglas Nass.. 7

要计算一个视图底部与另一个视图顶部之间的距离:

View oneView = ...;
View otherView = ...;

RectF oneRect = calculeRectOnScreen(oneView);
RectF otherRect = calculeRectOnScreen(otherView);

float distance = Math.abs(oneRect.bottom - otherRect.top);

util方法:

public static RectF calculeRectOnScreen(View view) {
    int[] location = new int[2];
    view.getLocationOnScreen(location);
    return new RectF(location[0], location[1], location[0] + view.getMeasuredWidth(), location[1] + view.getMeasuredHeight());
}

在某些情况下,您需要替换view.getLocationOnScreento view.getLocationInWindow.

1 个回答
  • 要计算一个视图底部与另一个视图顶部之间的距离:

    View oneView = ...;
    View otherView = ...;
    
    RectF oneRect = calculeRectOnScreen(oneView);
    RectF otherRect = calculeRectOnScreen(otherView);
    
    float distance = Math.abs(oneRect.bottom - otherRect.top);
    

    util方法:

    public static RectF calculeRectOnScreen(View view) {
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        return new RectF(location[0], location[1], location[0] + view.getMeasuredWidth(), location[1] + view.getMeasuredHeight());
    }
    

    在某些情况下,您需要替换view.getLocationOnScreento view.getLocationInWindow.

    2023-02-13 16:05 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有