我正在实现一个自定义 View ,我希望能够在运行时更改它的大小。
简化问题:我需要在此 View 中显示位图,但由于它经常刷新,我想扩展 SurfaceView。
问题是我失去了 ImageView 的自动调整大小功能。
所以我想声明一个方法 setCustomBitmap(Bitmap bmp) 并根据该位图的宽度和高度(保持纵横比)调整 View 尺寸(在当前或下一次显示 View 时)。
我应该使用什么方法?我想 setWidth() 和 setHeight() 不是最好的主意
最佳答案
由于您正在扩展 SurfaceView,因此您可以覆盖 onMeasure()
方法。您传递给父类(super class)(通过 super.onMeasure()
)的 MeasureSpec 实例将决定 SurfaceView 的大小。您可以使用位图的尺寸来制作每个 MeasureSpec。
例如:
protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec ) {
int parentViewWidth = MeasureSpec.getSize( widthMeasureSpec );
int parentViewHeight = MeasureSpec.getSize( heightMeasureSpec );
// ... take into account the parent's size as needed ...
super.onMeasure(
MeasureSpec.makeMeasureSpec( bitmap.width(), MeasureSpec.EXACTLY ),
MeasureSpec.makeMeasureSpec( bitmap.height(), MeasureSpec.EXACTLY ) );
}
关于java - Android自定义 View 中的可变大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12698866/