开发者

How I can draw an existent Canvas on another Canvas?

Now I need to draw a new Canvas in an existent Canvas (the parent Canvas), like Bitmap's works.

The logic is this:

  • Each Sprite can have others Sprite nodes (LinkedList<Sprite> nodes);
  • If don't have nodes (nodes = null) then, will draw the (Bitmap) Sprite.image directly to parent canvas, received on update method, like (currently working):

    public void update(Canvas canvas){
        if(this.nodes == null){
            canvas.drawBitmap(this.image, ...);
        }
        ...
    }
    
  • If it have nodes, I need create a new Canvas, draw nodes bitmap on this, and draw the new Canvas on parent Canvas. This don't works, but the idea is lik开发者_运维问答e this:

    public void update(Canvas canvas){
        ...
        else { // this.nodes != null
            Canvas newCanvas = new Canvas();
    
            for(Sprite node: this.nodes){
                node.update(newCanvas);
            }
    
            // Canvas working like Bitmap! (?)
            canvas.drawCanvas(newCanvas, this.x, this.y, this.paint);
        }
    }
    

Real example usage: well, I have a Sprite called CarSprite. The CarSprite have a private class called WheelSprite extends Sprite. The CarSprite implements two nodes (two dimensional example) of WheelSprite, that will be positioned in the CarSprite to seems the whell of car. So far, no problem.

But if CarSprite is affected by a devil one object in the level, this will be turn transparent. I will do, for instance, objectOfCarSprite.paint.setAlpha(127);. The problem is, if I do it (currently working mode), only the car bitmap will turn transparent, but not the well, because it is drawed directly to global Canvas object.

This part does not influence much: currently, I'm getting the parent (of parentN...) Paint object alpha, and with some math, I get a transparent solution to wheel that works almost as well I need, but if, for instance, the WheelSprite object is over car bitmap, is possible to see the ground of car, like picture.

Exists a better way to do like I want, or only like work currently?

How I can draw an existent Canvas on another Canvas?


I do it. But is very slow, but works fine.

    final Bitmap split = Bitmap.createBitmap(GameActivity.screenWidth,
        GameActivity.screenHeight,
        Bitmap.Config.ARGB_8888);
    final Canvas subCanvas = new Canvas(split);

    for(final Sprite sprite: this.nodes) {
        sprite.update(subCanvas);
    }

    canvas.drawBitmap(split, this.x, this.y, this.paint);
  1. First we need have a Canvas object (here just canvas);
  2. After, we need make a Bitmap where we will draw. This need get a width and height from current canvas. I used a shortcut on this case;
  3. Next, we need make a new Canvas, it will be passed to Sprite.nodes;
  4. After all, we need draw the bitmap on global canvas;

Note: this works very well, but affect to much the speed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜