java 使用可从资源绘制的位图初始化位图变量不起作用 - 使用 ANDROID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11890838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:47:52  来源:igfitidea点击:

Initializing Bitmap variable with bitmap drawable from resources is not working - using ANDROID

javaandroidbitmapandroid-canvasandroid-resources

提问by a_schimpf

I use the following code to initialize my bitmap variable:

我使用以下代码来初始化我的位图变量:

Bitmap bitmap = ((BitmapDrawable)this.model.gameView.context.getResources().getDrawable(R.drawable.pic1)).getBitmap();

When I try to log the width of that bitmap, the log does not even output anything for that call.

当我尝试记录该位图的宽度时,日志甚至不为该调用输出任何内容。

I know it's making it to that line, because I traced the code.

我知道它正在到达那条线,因为我跟踪了代码。

Also, when I try to do canvas.draw for the bitmap, nothing is drawn on the screen.

此外,当我尝试为位图执行 canvas.draw 时,屏幕上没有绘制任何内容。

Everything I draw with rectangles works fine.

我用矩形绘制的所有东西都可以正常工作。

My picture resource is a PNG.

我的图片资源是 PNG。

Any help is appreciated!

任何帮助表示赞赏!

采纳答案by a_schimpf

Just figured it out. It had nothing to do with the method of bitmap loading I used. It was a logical error on my part. My code accidentally reached a case where my bitmap became null, and it tried to draw the null resource on the canvas.

刚刚想通了。它与我使用的位图加载方法无关。就我而言,这是一个逻辑错误。我的代码不小心遇到了位图变为空的情况,它试图在画布上绘制空资源。

回答by corecase

Try something like this for your bitmap class.

为您的位图类尝试类似的操作。

public class DrawBitmap extends View
{
    Bitmap bitmap;

    public DrawBitmap(Context content)
    {
        super(content);

        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.pic1);
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);
        canvas.drawColor(Color.BLACK);//whatever color you want, make sure it's not the same as your image
        canvas.drawBitmap(bitmap, (canvas.getWidth()), 0, null);
    }
}

Main Class

主班

public class Main extends Activity 
{

    DrawBitmap myView;

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        myView = new DrawBitmap(this);
        setContentView(myView);
    }
}

回答by Serdar Samanc?o?lu

Try using BitmapFactory.decodeResource Have a look at the answer in this topic: How to convert a Drawable to a Bitmap?

尝试使用 BitmapFactory.decodeResource 看看本主题中的答案: 如何将 Drawable 转换为位图?