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

时间:2012-01-26 08:24:56

标签: android view background paint android-canvas

我通过从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");
    }
}

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

2 个答案:

答案 0 :(得分:9)

您实际上不想将绘制到您加载的位图,您只想在Canvas上绘制它,因此您应该使用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);
        }
    }
}

你也可以让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));
        }
    }
}

答案 1 :(得分:0)

我担心你会得到OutOfMemoryError,因为在视图生命周期中多次调用onDraw,并且每次为新位图分配内存。只需在您的视图的构造函数中创建类的bg成员(可能是 - static)并仅加载一次。并且不要忘记在视图分离时回收位图。