Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

draw object/image on canvas

Tags:

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. :)

like image 915
lulala Avatar asked Jan 31 '10 17:01

lulala


People also ask

Can you draw on an image in canvas?

Definition and Usage. The drawImage() method draws an image, canvas, or video onto the canvas. The drawImage() method can also draw parts of an image, and/or increase/reduce the image size. Note: You cannot call the drawImage() method before the image has loaded.

How do I put a picture on canvas?

Importing images into a canvas is basically a two step process: Get a reference to an HTMLImageElement object or to another canvas element as a source. It is also possible to use images by providing a URL. Draw the image on the canvas using the drawImage() function.


2 Answers

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);     } } 
like image 174
Emlyn Avatar answered Sep 22 '22 14:09

Emlyn


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);     } } 
like image 44
Nivish Mittal Avatar answered Sep 23 '22 14:09

Nivish Mittal