Canvas.getClipBounds是否会分配一个Rect对象?

4
在我的自定义视图中,我正在考虑使用Canvas.getClipBounds()来优化我的onDraw方法(这样每次调用时只绘制必要的内容)。
然而,我仍然希望绝对避免任何对象创建...
因此,我的问题是:每次调用getClipBounds()时,是否会分配一个新的Rect?还是它只是回收一个单一的Rect?
如果它分配了一个新的对象,那么我可以通过使用getClipBounds(Rect bounds)来节省这个开销,它似乎使用传递的Rect而不是它自己的Rect。
(在你大喊过早优化之前,请考虑当它放置在ScrollView中时,onDraw可能每秒被调用多次

看起来,如果您对性能比较敏感,您可能更喜欢获取调用者提供的矩形的简化语义版本的getClipBounds(),而不管另一种版本是否具有某些奇怪的回收优化。 - Don Hatch
@DonHatch 确实如此。但这确实是问题的一部分——备用版本是否分配了 Rect。接受的答案涵盖了这两个问题。请记住,当时撰写这个问题(大约 6 年前)时,查看 Android 源代码远非易事... - yydl
2个回答

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;
}

回答你的问题,使用 getClipBounds(Rect bounds) 可以避免创建一个对象,但是每次调用 getClipBounds() 都会创建一个新的 Rect() 对象。


0

“getClipBounds()”的实际方法声明如下:

  1. public boolean getClipBounds (Rect bounds) 因此,每次调用时不会创建一个新的 Rect 对象。它会使用你作为参数传递给这个函数的 Rect 对象。 我建议你查看一下这个链接enter link description here

什么?我不明白。正如我在问题中所写的那样,有两个不同的方法调用。一个需要一个矩形,而另一个则不需要。我正在询问不需要矩形的那个方法。 - yydl
抱歉给您带来不便,但为了避免每次调用方法时创建Rect对象,您应该像Luis所说的那样使用getClipBounds(Rect bounds)方法。 - appdroid

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接