如何在 onMeasure 之后在自定义 surfaceview 中分配位图?

How to allocate a bitmap in custom surfaceview after onMeasure?

我有一个自定义 SurfaceView,init 函数加载所有位图并从构造函数调用它,但我想调整位图的大小,我只能在 onMeasure 之后和 onDraw.This 之前执行此操作是我的 OnMeasure 方法我的自定义 SurfaceView:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    measuredHeight = MeasureSpec.getSize(heightMeasureSpec);
    measuredWidth = MeasureSpec.getSize(widthMeasureSpec);
    scrollableBg = Bitmap.createScaledBitmap(srcScrollableBg, measuredWidth, measuredHeight, true);
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

IDE 说 "Avoid object allocations during draw/layout operations (preallocate and reuse instead)" 用于 scrollableBg 分配,但我不能在初始化中执行此操作,因为我没有 measuredWidth 和 measuredHeight...

考虑使用 onLayout:

protected void onLayout (boolean changed, int left, int top, int right, int bottom)

Added in API level 1 Called from layout when this view should assign a size and position to each of its children. Derived classes with children should override this method and call layout on each of their children.

onMeasure之后调用。一个好的做法是仅在 changed == true 时分配您的对象:您将从 IDE 收到相同的警告,但这样您可以安全地忽略它。

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    if (changed) {
        // allocate bitmap
        // get width with right - left
        // get height with bottom - top
    }
    super.onLayout(changed, left, top, right, bottom);
}