m4n07
m4n07

Reputation: 2287

Can we have two canvases in an activity ? (OR) Having a canvas outside the onDraw() is not working

@Override
        protected void onDraw(Canvas canvas) {
        // Draw graphic objects
         .....
             }

         public void displayCalc(){

           //Do some calculation & display results near these graphic objects
            String result = String.valueOf(value);

             //Do some calculation

              //Display Calculated values
             Canvas c =new Canvas();
             Paint paint = new Paint();
             paint.setStyle(Paint.Style.FILL);
             paint.setAntiAlias(true);
             paint.setColor(Color.WHITE);
             c.drawText(result,200,300,paint);
                     }

But if i have the same thing in the function onDraw it works fine. I would like to know why or what changes i have to make to get it working

   @Override
    protected void onDraw(Canvas canvas) {

    // Draw graphic objects 
    //Do some calculation & display results near these graphic objects
     .....
     String result = String.valueOf(value);

        //Display Calculated values
         Paint paint = new Paint();
         paint.setStyle(Paint.Style.FILL);
         paint.setAntiAlias(true);
         paint.setColor(Color.WHITE);
         canvas.drawText(result,200,300,paint);
}

Upvotes: 0

Views: 3981

Answers (2)

forsvarir
forsvarir

Reputation: 10839

If you're trying to implement some kind of double buffering, you might want to take a look at this

I think your problem is that you need to create a bitmap, then attach the canvas to it, something like:

Bitmap bitmap = Bitmap.createBitmap(width, height, Config.RGB_565);
Canvas c = new Canvas(bitmap);

// then draw to the canvas..
// and when you're happy, draw the bitmap onto the canvas supplied to onDraw.

Just creating a canvas, doesn't make it appear on the screen.

You may also want to take a look at: this tutorial

If you have a surfaceView, then you can do something like this (don't have a compiler, but hopefully you get the gist):

SurfaceView view = (SurfaceView)findViewById(R.id.view);

SurfaceHolder holder = view.getHolder(); // save this where it can be accessed by your function

Canvas c 
try  {
    c = holder.lockCanvas();
    // draw stuff
}
finally {
    if(null != c) {
        holder.unlockCanvasAndPost(c);
    }
}

Upvotes: 1

WarrenFaith
WarrenFaith

Reputation: 57672

If you want to have two SurfaceViews, than simply add them to your layout and give them both an own thread (or combine both drawings in one thread).

I don't get it why you want to draw on a separate canvas in your first method sample... Maybe you provide more information for what you try to achieve.

Upvotes: 0

Related Questions