28

Is there another way to draw an object on a canvas in android?

This code inside draw() doesn't work:

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pushpin);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);

Well actually, it's working on my 1st code but when I've transfered this to another class called MarkOverlay, it's not working anymore.

  markerOverlay = new MarkerOverlay(getApplicationContext(), p);
                      listOfOverlays.add(markerOverlay);  

What parameter should I pass to MarkerOverlay to make this code work? The error is somewhere in getResources().

FYI, canvas.drawOval is perfectly working but I really want to draw an Image not an Oval. :)

lulala
  • 637
  • 4
  • 12
  • 21

2 Answers2

41

I prefer to do this as it only generates the image once:

public class CustomView extends View {

    private Drawable mCustomImage;

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mCustomImage = context.getResources().getDrawable(R.drawable.my_image);
    }

    ...

    protected void onDraw(Canvas canvas) {
        Rect imageBounds = canvas.getClipBounds();  // Adjust this for where you want it

        mCustomImage.setBounds(imageBounds);
        mCustomImage.draw(canvas);
    }
}
Roger C S Wernersson
  • 6,362
  • 6
  • 34
  • 45
Emlyn
  • 561
  • 5
  • 3
  • 10
    +1 for not making allocations or unpacking an image in onDraw – user1532390 Feb 15 '13 at 15:22
  • 1
    gives me this eclipse warning: Avoid object allocations during draw operations: Use Canvas.getClipBounds(Rect) instead of Canvas.getClipBounds() which allocates a temporary Rect – bhaskarc Dec 14 '13 at 06:40
  • 1
    This can be made even better if you follow the simple optimizer hits given by Eclipse. Ie. canvas.getClipBounds(imageBounds); mCustomImage.setBounds(imageBounds); Having a super fast onDraw is very important. – slott May 07 '15 at 07:30
  • `getResources().getDrawable()` is deprecated as of API 22. Use `ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);` instead. – Izaak Cornelis Jun 12 '20 at 18:17
26
package com.canvas;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;

public class Keypaint extends View {
    Paint p;

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        p=new Paint();
        Bitmap b=BitmapFactory.decodeResource(getResources(), R.drawable.icon);
        p.setColor(Color.RED);
        canvas.drawBitmap(b, 0, 0, p);
    }

    public Keypaint(Context context) {
        super(context);
    }
}
rodrigo-silveira
  • 12,607
  • 11
  • 69
  • 123
Nivish Mittal
  • 317
  • 3
  • 3