Draw background of custom View from .png file on A

2019-02-17 18:29发布

问题:

I created a custom View by extending from View. In onDraw() I managed to draw some circles and other stuff. But now I want to add a background from a resource (sd card or a stream) which is actually a map I download from our server and than draw on it. It's for 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");
    }
}

Somehow g.setBitmap(bg) keeps failing, I haven't looked at the image specs, but actually it's just a tux image (no 24 bits colors) of PNG format. Can someone give me some tips how to add a background image so I can draw on it? Thank you.

回答1:

You actually don't want to draw on to the bitmap you load, you just want to draw it on the Canvas, so you should use Canvas.drawBitmap(). You also really should not load a Bitmap in each onDraw(), do it in the constructor instead. Try this class:

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);
        }
    }
}

You can also let Android draw the bitmap in the background:

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));
        }
    }
}


回答2:

I'm afraid that you get OutOfMemoryError, cause onDraw is called many times during view lifecycle, and every time you are allocating memory for new bitmap. Just make bg member (maybe - static) of your class and load it only once - in your view's constructor. And don't forget to recycle bitmap on view's detaching.