您实际上不想绘制到您加载的位图,您只是想在画布上绘制它,所以您应该使用Canvas.drawBitmap()。你也真的不应该在每个onDraw()中加载一个位图,而是在构造函数中进行。试试这个类:
package com.example.android;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;
public class CustomView extends View {
private final Bitmap mBitmapFromSdcard;
public CustomView(Context context) {
this(context, null);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
mBitmapFromSdcard = BitmapFactory.decodeFile("/mnt/sdcard/download/tux.png");
}
@Override
protected void onDraw(Canvas canvas) {
Canvas g = canvas;
if (mBitmapFromSdcard != null) {
g.drawBitmap(mBitmapFromSdcard, 0, 0, null);
}
}
}
您也可以让Android为绘制位图背景:
package com.example.android;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.View;
public class CustomView extends View {
public CustomView(Context context) {
this(context, null);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
Bitmap bm = BitmapFactory.decodeFile("/mnt/sdcard/download/tux.png");
if (bm != null) {
setBackgroundDrawable(new BitmapDrawable(bm));
}
}
}
Martin, 非常感谢你为这个明确的例子。奇怪,我已经做了你的第一个例子,不知何故,它不工作!那是我开始迷路的地方。第二个是适应视野的房地产,这正是最终的结果。但你的第一个我更喜欢它,这样我可以在不修改尺寸的情况下定位图片。 – AndaluZ
当你尝试我的第一个例子时,究竟是什么不起作用?一个例外(如果是这样,什么例外)?屏幕上没有绘制任何东西?你在运行什么Android版本?你能提供你想要的确切代码吗? –
它可以与我的朋友一起工作,包括.png和.jpg。在您发布后,我仍然在播放并尝试一些图片,发现并非所有的.jpeg文件都能正常工作。当我使用像50 KB这样的小JPG图片时,它可以工作,但是当使用像600 KB这样的更大的JPG图片时,背景变成完全白色。我不知道它是否与图像大小有关,导致那些不起作用的图像比我的视图的房地产大得多。使用setBackgroundDrawable()确实有效,但它也会缩小到视图的实际大小。 – AndaluZ