我通过从 View 扩展创建了一个自定义 View。在 onDraw() 中,我设法绘制了一些圆圈和其他东西。但现在我想从资源(SD 卡或流)添加背景,这实际上是我从服务器下载的 map ,而不是在上面绘制。适用于 Android 8+
@Override
protected void onDraw(Canvas canvas) {
Canvas g = canvas;
String file = "/mnt/sdcard/download/tux.png";
Bitmap bg = null;
try {
bg = BitmapFactory.decodeFile(file);
g.setBitmap(bg);
} catch (Exception e) {
Log.d("MyGraphics", "setBitmap() failed according to debug");
}
}
不知何故 g.setBitmap(bg) 一直失败,我没有查看图像规范,但实际上它只是 PNG 格式的晚礼服图像(无 24 位颜色)。 有人可以给我一些提示,告诉我如何添加背景图像以便我可以在上面绘图吗? 谢谢。
最佳答案
您实际上不想在您加载的位图上绘制,您只想在 Canvas 上绘制它,因此您应该使用 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));
}
}
}
关于android - 在 Android 上从 .png 文件绘制自定义 View 的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9015441/