返回

Android ColorDrawable 源码剖析

Android

#

#

#

1. ColorDrawable 简介

ColorDrawable 是一个非常简单的 Drawable 子类,它只包含一个颜色值,用于绘制纯色图。在 Android 开发中,经常需要使用 ColorDrawable 来填充 View 的背景色,或者作为其他 Drawable 的遮罩层。

2. ColorDrawable 源码剖析

ColorDrawable 的源码非常简单,只有不到 100 行代码。它继承自 Drawable 类,并实现了 Drawable 接口中定义的所有方法。

2.1 构造函数

ColorDrawable 提供了两个构造函数:

  • ColorDrawable():创建一个不透明的 ColorDrawable,其颜色值为黑色。
  • ColorDrawable(int color):创建一个 ColorDrawable,其颜色值为指定的 color 参数。

2.2 绘制方法

ColorDrawable 的绘制方法 draw() 非常简单,它直接调用 Canvas 的 drawColor() 方法来绘制颜色。

@Override
public void draw(Canvas canvas) {
    canvas.drawColor(mColor, PorterDuff.Mode.SRC);
}

2.3 性能优化

ColorDrawable 的绘制非常简单,因此它的性能也非常好。但是,如果 ColorDrawable 被用于填充一个非常大的 View,则可能会出现性能问题。为了解决这个问题,ColorDrawable 提供了一个 mutate() 方法,可以将 ColorDrawable 转换为一个可变对象。

@Override
public Drawable mutate() {
    if (mState == null) {
        mState = new Drawable.ConstantState(mState, null);
    }
    return this;
}

当 ColorDrawable 被转换为一个可变对象后,它就可以被修改了。例如,可以修改它的颜色值。

ColorDrawable drawable = new ColorDrawable(Color.RED);
drawable.mutate().setColor(Color.BLUE);

3. ColorDrawable 的应用场景

ColorDrawable 在 Android 开发中有很多应用场景,以下列举了一些常见的场景:

  • 填充 View 的背景色
  • 作为其他 Drawable 的遮罩层
  • 创建纯色按钮
  • 创建纯色进度条

4. 总结

ColorDrawable 是一个非常简单但非常实用的 Drawable 子类。它可以用于填充 View 的背景色、创建纯色按钮、创建纯色进度条等。ColorDrawable 的源码非常简单,只有不到 100 行代码。它提供了两个构造函数、一个绘制方法和一个性能优化方法。ColorDrawable 在 Android 开发中有很多应用场景,它是一个非常有用的工具。