开发者

Trying to modify simple Android shape tutorial to use images, having trouble

开发者 https://www.devze.com 2023-04-01 01:55 出处:网络
I am following the below tutorial: http://www3.ntu.edu.sg/home/ehchua/programming/android/Android_2D.html

I am following the below tutorial:

http://www3.ntu.edu.sg/home/ehchua/programming/android/Android_2D.html

In it,

Canvas canvas.drawOval();

is called in order to have a default circle drawn, that bounces around. My normal way of learning a new graphics framework is to build on this, and then upgrade to images. Normally, this is very simple, but I"m having trouble here. There is no equivalent "drawImage" to the drawOval command (which I'm more used to).

Instead, I'm trying to figure out "drawables".

So, following another tutorial (specifically the default Android "snake" game), I tried doing:

Resources r = this.getContext().getResources();

in my view, then passed the resource object to my ball object, to get:

img = r.getDrawable(R.drawable.ball);

where ball is a file stored in /res/drawable/ball.png

In the ball objects draw method (which I call in the view's onDraw method), I have:

img.draw(canvas);

canvas is passed from onDraw, which is itself passed a canvas. I don't really understand who is calling onDraw (I assume some internal process), but this differs from the snake example where they make their own canvas?

Either way, this开发者_开发百科 doesn't seem to work. I am not getting any image, or any errors. I know that img is at least populated (its not null or anything), but other than that I don't really know what to do...

If this were Ruby (my most familiar language), I'd call inspect on the img to see if actually has anything in it...is there an equivalent for Java (or should I fool around with break points)?

Is there anything obvious that I'm doing wrong? Can I not use the default canvas I'm being passed, even though I clearly can for drawing simple shapes?


Ah, I figured it out:

With the draw oval method, I needed to set the bounds like so:

RectF bounds.set(ballX-ballRadius, ballY-ballRadius, ballX+ballRadius, ballY+ballRadius);

But for the drawable object, I have to go one step further and say

img.setBounds(bounds); 

and make bounds be a Rect instead of a RectF.

Once that is done, voila, things are rendering.

It didn't occur to me at first that the bounds are how things know where to render themselves, and while you pass the bounds to an oval, you have to SET them to a drawable.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号