简体   繁体   English

使用画布在位图中绘制在Android视图中不起作用

[英]Draw in bitmap using canvas doesn't work in android view

I'm trying to use onDraw method and canvas to draw some items in a bitmap and cache it to draw it again and don't call onDraw again 我正在尝试使用onDraw方法和canvas onDraw图中绘制某些项目,并将其缓存以再次绘制,而不再调用onDraw

This is part of my code : 这是我的代码的一部分:

@Override
    protected void onDraw(Canvas canvas) {

        super.onDraw(canvas);

        if (mCacheDrawing == null) {
            mCacheDrawing = Bitmap.createBitmap(mScrollWidth, mScrollHeight, Config.RGB_565);
            canvas.setBitmap(mCacheDrawing);

            for (int i = 0; i < mIcons.size(); i++) {

                prepareItem(canvas, paint, mIcons.get(i));
            }

            canvas.save();
        } else {
            canvas.setBitmap(mCacheDrawing);
        }
    }

The code is not working and show me an empty screen, can any one help me please? 代码无法正常工作,显示空白屏幕,有人可以帮我吗?

EDIT : I have found the following post and it help me to solve the problem >> https://groups.google.com/forum/#!topic/android-beginners/6pO8SJN3CTY 编辑:我发现以下帖子,它可以帮助我解决问题>> https://groups.google.com/forum/#!topic/android-beginners/6pO8SJN3CTY

and my working code now is following : 现在我的工作代码如下:

@Override
    protected void onDraw(Canvas canvas) {

        super.onDraw(canvas);

        if (mCacheDrawing == null) {

            mCacheDrawing = Bitmap.createBitmap(mScrollWidth, mScrollHeight, Config.RGB_565);
            mCanvas = new Canvas(mCacheDrawing);
            for (int i = 0; i < mIcons.size(); i++) {

                prepareItem(mCanvas, paint, mIcons.get(i));
            }
        } 

        canvas.drawBitmap(mCacheDrawing,new Rect (0,0, mScrollWidth, mScrollHeight), new Rect (0,0, mScrollWidth, mScrollHeight), paint);
    }

Well i can't figure out functionality of your code as its a snippet from a section, But what I can figures out is the reason. 好吧,我无法从部分代码中了解您的代码的功能,但是我能弄清楚的是原因。 quick check 快速检查

  1. If you trying to draw bitmaps from a view, make sure drawing cache is enabled/ 如果您尝试从视图绘制位图,请确保已启用图形缓存/
  2. canvas.drawBitmap , this is the API for drawing a Bitmap over a canvas and not setBitmap canvas.drawBitmap ,这是用于在画布上绘制位图而不是setBitmap

you can use save and restore method of canvas accordingly. 您可以相应地使用画布的保存和还原方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM