【发布时间】:2011-08-21 20:45:17
【问题描述】:
我正在扩展 ImageView 以便在视图中手动缩放图像。我想缩放图像以填充自定义视图的宽度,然后将其绘制到画布上,但是,我无法使用 this.getWidth() 获取视图宽度
它只返回 0,因为视图尚未绘制,因此尺寸为 0 x 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"
/>
自定义类如下:
public class BackgroundView extends ImageView {
private Paint paint;
private Bitmap background;
public BackgroundView(Context context) {
super(context);
paint = new Paint();
loadBitmap();
}
public BackgroundView(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
loadBitmap();
}
public void loadBitmap() {
BitmapDrawable src = (BitmapDrawable) this.getDrawable();
background = src.getBitmap();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(background, 0, 0, paint);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
我的 Main.java 类是:
public class Main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
我不能使用Bitmap.createScaledBitmap(background, view.getWidth(), view.getHeight(), false)
由于尚未绘制视图,此时我将如何缩放图像以填充视图/屏幕宽度?
提前致谢。
【问题讨论】:
标签: android view canvas bitmap imageview