在Android上从.png文件中绘制自定义视图的背景

And*_*luZ 5 android background view paint android-canvas

我通过从View扩展创建了一个自定义View.在onDraw()中,我设法绘制了一些圆圈和其他东西.但是现在我想从资源(SD卡或流)添加背景,这实际上是我从服务器下载的地图,而不是在它上面绘制.它适用于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");
    }
}
Run Code Online (Sandbox Code Playgroud)

不知怎的,g.setBitmap(BG)不断失败,我没有看过的图像规格,但实际上它只是一个晚礼服的图像PNG格式的(无24位色).有人可以给我一些如何添加背景图片的技巧,以便我可以在上面绘图吗?谢谢.

Mar*_*lts 9

你其实并不想画的位图加载,你只是想绘制在画布上,所以你应该使用Canvas.drawBitmap().你也真的不应该在每个onDraw()中加载一个Bitmap,而是在构造函数中做.试试这堂课:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

你也可以让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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)