Draw a circle on an existing image

I am trying to draw a circle on an image that is placed as res/drawable/schoolboard.png . The image fills the activity background. The following does not work:

  Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.schoolboard); Paint paint = new Paint(); paint.setAntiAlias(true); paint.setColor(Color.BLUE); Canvas canvas = new Canvas(bitmap); canvas.drawCircle(60, 50, 25, paint); ImageView imageView = (ImageView)findViewById(R.drawable.schoolboard); imageView.setAdjustViewBounds(true); imageView.setImageBitmap(bitmap); 

Any help would be greatly appreciated. thanks.

+7
android android canvas
source share
2 answers

There are some errors in your code: firstly, you cannot give a reference identifier for drawable in findViewById so I think you mean something like this

 ImageView imageView = (ImageView)findViewById(R.id.schoolboard_image_view); 

schoolboard_image_view is the id of the image in your xml layout (check your layout for the correct id)

 BitmapFactory.Options myOptions = new BitmapFactory.Options(); myOptions.inDither = true; myOptions.inScaled = false; myOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// important myOptions.inPurgeable = true; Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.schoolboard,myOptions); Paint paint = new Paint(); paint.setAntiAlias(true); paint.setColor(Color.BLUE); Bitmap workingBitmap = Bitmap.createBitmap(bitmap); Bitmap mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true); Canvas canvas = new Canvas(mutableBitmap); canvas.drawCircle(60, 50, 25, paint); ImageView imageView = (ImageView)findViewById(R.id.schoolboard_image_view); imageView.setAdjustViewBounds(true); imageView.setImageBitmap(mutableBitmap); 

Please use the correct image id for:

ImageView imageView = (ImageView) findViewById ( R.id.schoolboard_image_view );

+10
source share

First of all, you need to create a new bitmap, because the bitmap from the BitmapFactory.decodeResource () method is unchanged. You can do this with the following code:

 Bitmap canvasBitmap = Bitmap.createBitmap([bitmap_width], [bitmap_height], Config.ARGB_8888); 

Use this bitmap in the Canvas constructor. Then draw a bitmap on the canvas.

 Canvas canvas = new Canvas(canvasBitmap); canvas.drawBitmap(bitmap, 0, 0, bitmapPaint); canvas.drawCircle(60, 50, 25, paint); 

Also R.drawable.schoolboard is not a valid view identifier.

ImageView imageView = (ImageView) findViewById (R.drawable.schoolboard);

+5
source share

All Articles