Android: drawing a bitmap in a specific place, refusing to draw

Let me start by saying that I'm basically new to writing Java, so I would like a complete explanation. This is not just an eruption of code, but what gives some on the site, why and where it should be

I'm currently trying to write an application, however, I am having problems with Canvas and drawing a bitmap that I would like on it. This is my code for drawing an image:

Canvas canvas = null; Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.image); canvas.drawBitmap(image, 10, 800, null); 

This method (expectantly) throws a Null Pointer exception. However, defining canvas as null is the only option that Eclipse gives me. When trying to define it as

 Canvas canvas = new Canvas(); 

Android just refuses to draw a bitmap. I am sure my image is in res / drawable / image. If that helps, the image is saved as "image.png"

How do I get Android to display / display my image / bitmap in a specific place? I asked him to draw an image (10x800)?

+4
source share
1 answer

Writing nonsense that solves a compiler error does not alter the fact that this is nonsense! :)

You should get a reference to the Canvas object in another way. You can be more specific about what exactly you are trying to do so that we can suggest how you should do it. (For example, are you trying to just display the image along with some other views? Are you trying to create a custom view? You might just want to consider using ImageView)

Edit:

You should read about Android architecture at developer.android.com. If you're just trying to display an image, there may be no reason to use the canvas directly. However, you can draw in a custom view by extending the view class

 class myView extends View{ Bitmap bm; loadBitmap() { bm = BitmapFactory.decodeResource(getResources(), R.drawable.image); } @Override public void draw(Canvas c) { c.drawBitmap(bm, XCORD, YCORD, null); } } 

if you don’t need a custom view, just use the ImageView class

 class MyActivty extends Activity{ @Override public void onCreate(Bundle b) { super.onCreate(b); ImageView iv = new ImageView(this); iv.setImageResource(R.drawable.pic); setContentView(iv); } } 

Warning: I wrote these method calls from the top of my head; they may be slightly disabled.

+4
source

Source: https://habr.com/ru/post/1393577/


All Articles