【问题标题】:Android Rect width and height differs from original dimensionsAndroid Rect 宽度和高度与原始尺寸不同
【发布时间】:2016-06-29 19:48:13
【问题描述】:

我正在跟踪一个问题,为什么 Rect.intersects 函数在我的 Android 应用程序中不起作用,并发现我的一个矩形的宽度和高度不正确。

ImageView tt = (ImageView)findViewById(R.id.tt);
Rect newInRect = new Rect(421, tt.getTop(), tt.getRight(), tt.getBottom());
Log.d("Size comparison", String.format("getRight %d, getLeft: %d | Width: %d, Height: %d", tt.getRight(), tt.getLeft(), newInRect.width(), newInRect.height()));

输出为:“大小比较:getRight 296,getLeft:144 | 宽度:-124,高度:152”

getRight() 和 getBottom() 函数不代表宽度和高度吗? 为什么它们返回不同的值?哪一个是正确的? 我的意图是使 Rect 与名为 tt 的 ImageView 大小完全相同,但 X 坐标不同。我该怎么做?

【问题讨论】:

    标签: java android


    【解决方案1】:

    不行,看看Rect的实现:

     /**
     * @return the rectangle's width. This does not check for a valid rectangle
     * (i.e. left <= right) so the result may be negative.
     */
    public final int width() {
        return right - left;
    }
    
    /**
     * @return the rectangle's height. This does not check for a valid rectangle
     * (i.e. top <= bottom) so the result may be negative.
     */
    public final int height() {
        return bottom - top;
    }
    

    您只是比较错误的值。尝试比较两种情况下的宽度和高度 (Rect's)。

    【讨论】:

      【解决方案2】:

      获取宽度和高度:

      ViewGroup.LayoutParams layoutParams = tt.getLayoutParams();
      int h = layoutParams.height;
      int w = layoutParams.width;
      

      【讨论】:

        【解决方案3】:

        getLeft()getRight()getBottom()getTop() 返回相对于父级的值,而不是屏幕坐标。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-11-02
          • 1970-01-01
          • 1970-01-01
          • 2016-06-07
          • 1970-01-01
          • 2018-02-26
          • 1970-01-01
          • 2018-11-08
          相关资源
          最近更新 更多