Android Rect介绍

原文地址:Android 图形基础类Rect,扎实基础助腾飞_王亟亟的博客-CSDN博客

Rect


这是一个我们常用的一个“绘画相关的工具类”,常用语描述长方形/正方形,他只有4个属性

    public int left;
    public int top;
    public int right;
    public int bottom;

这4个属性描述着这一个“方块”,但是这有一个知识点需要理清楚,先看这张图

本Rect最左侧到屏幕的左侧的距离是 left 
本Rect最上面到屏幕上方的距离是 top 
本Rect最右侧到屏幕左侧的距离是 right 
本Rect最下面到屏幕上方的距离是 bottom

这四个属性不单单描述了这个 长方形4个点的坐标,间接的描述出这个长方形的尺寸

长 = bottom - top 
宽 = right - left

这部分的知识可以看:What does top, left, right and bottom mean in Android Rect object - Stack Overflow

构造函数

public Rect() { }

public Rect(int left, int top, int right, int bottom) {
        this.left = left;
        this.top = top;
        this.right = right;
        this.bottom = bottom;
    }

 public Rect(Rect r) {
        if (r == null) {
            left = top = right = bottom = 0;
        } else {
            left = r.left;
            top = r.top;
            right = r.right;
            bottom = r.bottom;
        }
    }

3个构造函数都是围绕着初始化这4个属性来做的,无论是传过来一个新Rect对象,还是传入具体的尺寸。

常用的那些方法


获取“宽”

  public final int width() {
        return right - left;
    }

获取“高”

 public final int height() {
        return bottom - top;
    }


有效性的判断

因为left是最左侧,right比left还小不就不成形了么?
宽高同是如此

public final boolean isEmpty() {
        return left >= right || top >= bottom;
    }


全部置0操作

 public void setEmpty() {
        left = right = top = bottom = 0;
    }


设置参数方法,和构造函数的区别仅在于不会创建新对象

  public void set(int left, int top, int right, int bottom) {
        this.left = left;
        this.top = top;
        this.right = right;
        this.bottom = bottom;
    }

整体实现不是很复杂,就是为了形容描绘,实现一个 “长方形”的概念。

  • 15
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值