您實際上不想繪製到您加載的位圖,您只是想在畫布上繪製它,所以您應該使用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