user650309
user650309

Reputation: 2899

Drawing to a created Bitmap from onDraw()

I'm trying to draw to a Bitmap so I can put my custom view inside an imageView.The code within the onDraw method is:

    public void onDraw(Canvas canvas) {     

    Bitmap drawGraph = Bitmap.createBitmap(canvas.getWidth(),canvas.getHeight(),Bitmap.Config.ARGB_8888);       
    canvas.setBitmap(drawGraph);    
    canvas.drawBitmap(drawGraph, 0, 0, bgPaint);

My problem is that if I try to use a Bitmap in this way, I just get a black screen. I know that the rest of my code works as it displays if I don't try to draw to a bitmap.

If I comment out the line

canvas.setBitmap(drawGraph);

Then everything works perfectly, so this is the problem but I dont know why.

where am I going wrong?

Upvotes: 1

Views: 7694

Answers (3)

ucMax
ucMax

Reputation: 5438

AFAIK The most efficient way is to override drawable setters.

@Override
public void setImageBitmap(Bitmap bm) {
    bmp = bm;
}

@Override
public void setImageDrawable(Drawable drawable) {
    try {
        bmp = ((BitmapDrawable) drawable).getBitmap();
    } catch (Exception e){
        log(e.toString());
    }
}

Upvotes: 0

user650309
user650309

Reputation: 2899

Turns out I did have to create a second canvas. My working code is below just for anyone who might need it:

    public void onDraw(Canvas canvas) {

    Canvas singleUseCanvas = new Canvas();      

    drawGraph = Bitmap.createBitmap(canvas.getWidth(),canvas.getHeight(),Bitmap.Config.ARGB_8888);      
    singleUseCanvas.setBitmap(drawGraph);   

    canvas.drawBitmap(drawGraph, 100, 100, bgPaint);

Upvotes: 6

Mister Smith
Mister Smith

Reputation: 28168

I think is the canvas and canvas2 dichotomy. Try to use only canvas2 (the parameter) to draw.

Upvotes: 1

Related Questions