Android 如何在onMeasure之后在自定义surfaceview中分配位图?
我有一个自定义的SurfaceView,init函数加载所有位图并从构造函数调用,但我想调整位图的大小,我只能在onMeasure之后和onDraw之前进行此操作。这是自定义SurfaceView中的onMeasure方法:Android 如何在onMeasure之后在自定义surfaceview中分配位图?,android,android-layout,android-bitmap,Android,Android Layout,Android Bitmap,我有一个自定义的SurfaceView,init函数加载所有位图并从构造函数调用,但我想调整位图的大小,我只能在onMeasure之后和onDraw之前进行此操作。这是自定义SurfaceView中的onMeasure方法: @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { measuredHeight = MeasureSpec.getSize(heightMeasureS
@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对scrollableBg分配说“在绘制/布局操作期间避免对象分配(而是预分配和重用)”,但我不能在初始化中这样做,因为我没有测量的宽度和测量的高度…考虑使用
onLayout
:
仅限受保护的空布局(布尔值已更改、整数左侧、整数顶部、整数
右,整数(下)
当此视图应分配
每个子对象的大小和位置。具有
子级应重写此方法并在每个子级上调用layout
孩子们
它在测量的之后调用。一个好的做法是只在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);
}
考虑使用onLayout
:
仅限受保护的空布局(布尔值已更改、整数左侧、整数顶部、整数
右,整数(下)
当此视图应分配
每个子对象的大小和位置。具有
子级应重写此方法并在每个子级上调用layout
孩子们
它在测量的之后调用。一个好的做法是只在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);
}