Draw with a Canvas over an Image in Android/Java

邮差的信 提交于 2019-12-25 15:15:34

问题


I try to draw on a Canvas, where the background is an loaded Image in Android. It works just fine without the backgroundimage:

background = (ImageView)view.findViewById(R.id.Background);
Bitmap bitmap = Bitmap.createBitmap(canvasSize,canvasSize,Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
background.setImageBitmap(bitmap);

Im passing that canvas to another class and draw on it. That works fine.

But when I do this:

background = (ImageView)view.findViewById(R.id.Background);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); //Just to test

canvas = new Canvas(bitmap); 
//or this
canvas = new Canvas(bitmap.copy(Bitmap.Config.ARGB_8888, true));

background.setImageBitmap(bitmap);

It doesn't draw over the image, so you can't see the point. Here is the code from the other class where I use this canvas to draw:

canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
canvas.drawCircle( (float)sObject.getSideGforce()*mult+add, 
(float)sObject.getFrontRearGforce()*mult+add, 15*V.LOGICAL_DENSITY, dot);                                                                                                                          

My goal is to create a Canvas with a custom size which has an image as a background where I can draw on. Its a Gforce Display, so the Image will be some circles with numbers and the canvas will draw a point over it so you can see how many Gs you are pulling. Like I already said it works perfectly without the background. And I dont want to redraw the background every single time I reposition the point. So the background should be static and the point should on the canvas is dynamic ( at 100hz ). Thanks in advance.

SOLUTION: It works with this code.

view.setBackgroundResource(R.drawable.ic_launcher);

I just had to set the Background of my view. It stretches the image to the size of my fragment, but thats OK.


回答1:


BitmapFactory.decodeResource() creates and immutable Bitmap, so there is why you can't change it.

You need to create a Bitmap as your working code, then use canvas.drawBitmap() to draw the Bitmap you want in the background. And then draw the things you want.

EDIT: Or use setBackground() with the background and only draw the points on the canvas.



来源:https://stackoverflow.com/questions/26016655/draw-with-a-canvas-over-an-image-in-android-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!