Android 在自定义图像视图中缩放图像

Android 在自定义图像视图中缩放图像,android,view,canvas,bitmap,imageview,Android,View,Canvas,Bitmap,Imageview,我正在扩展ImageView,以便在视图中手动缩放图像。我想缩放图像以填充自定义视图的宽度,然后将其绘制到画布上,但是,我无法使用this.getWidth() 它只返回0,因为视图尚未绘制,因此尺寸标注为0乘0 目前,我的main.xml中有以下内容: <com.android.myapp.BackgroundView android:id="@+id/background_view" android:layout_height="fill_parent" and

我正在扩展ImageView,以便在视图中手动缩放图像。我想缩放图像以填充自定义视图的宽度,然后将其绘制到画布上,但是,我无法使用
this.getWidth()
它只返回0,因为视图尚未绘制,因此尺寸标注为0乘0

目前,我的main.xml中有以下内容:

<com.android.myapp.BackgroundView
    android:id="@+id/background_view"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:src="@drawable/background"
    android:dither="true"
    />
我的Main.java类是:

public class Main extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
我不能用
Bitmap.createScaledBitmap(背景、视图.getWidth()、视图.getHeight()、false)

由于尚未绘制视图,此时如何缩放图像以填充视图/屏幕宽度


提前感谢。

我相信您想要做的事情也可以通过将ImageView与属性直接结合使用来实现。根据需要,使用fitXY或centerCrop

但要回答这个问题,只能在调用layout()之后使用getWidth()和getHeight()。因此,您应该能够使用onDraw方法中的值

您还可以使用另一种方法,这样就不必在内存中创建新的位图

public class Main extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }