android - 在 Android 上从 .png 文件绘制自定义 View 的背景

标签 android view background paint android-canvas

我通过从 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/

相关文章:

java - 膨胀 TableLayout 时出错

SQL - 将两个表的内容合并到一个表/ View 中

java - 为什么java后台进程很慢?

javascript - 我怎样才能让我的背景视频全屏 react ?

Javascript 随机背景右上固定

Android 房间持久性库

安卓:随机异常

android - 如何在android中显示欢迎屏幕?

sql - postgresql 在物化 View 上创建触发器

SQL View 与派生表