Canvas.getClipBounds是否分配Rect对象?

yyd*_*ydl 4 optimization android android-custom-view android-canvas

在我的自定义视图中,我正在研究使用Canvas.getClipBounds()来优化我的onDraw方法(这样我每次调用时都只绘制了绝对必要的东西).

但是,我仍然希望绝对避免任何对象创建......

因此,我的问题是:getClipBounds()每次调用时都会分配一个新的Rect吗?或者只是简单地回收一个Rect?

如果它正在分配一个新对象,我可以通过使用来保存这个费用getClipBounds(Rect bounds),这似乎使用传递的Rect而不是它自己的吗?


(你尖叫过早的优化之前,不要考虑放置在滚动型时,的onDraw可以被称为很多次每秒)

Lui*_*ano 10

我已经查看了Android 4.0.1的Canvas源代码,它如下:

/**
 * Retrieve the clip bounds, returning true if they are non-empty.
 *
 * @param bounds Return the clip bounds here. If it is null, ignore it but
 *               still return true if the current clip is non-empty.
 * @return true if the current clip is non-empty.
 */
public boolean getClipBounds(Rect bounds) {
    return native_getClipBounds(mNativeCanvas, bounds);
}


/**
 * Retrieve the clip bounds.
 *
 * @return the clip bounds, or [0, 0, 0, 0] if the clip is empty.
 */
public final Rect getClipBounds() {
    Rect r = new Rect();
    getClipBounds(r);
    return r;
}
Run Code Online (Sandbox Code Playgroud)

因此,回答你的问题,getClipBounds(Rect bounds)将使你免于创建一个对象,但getClipBounds()实际上会在每次调用时创建一个新的Rect()对象.