在Android中,如何使图像随机出现? [英] In Android, how to make an image randomly appear ??

查看:163
本文介绍了在Android中,如何使图像随机出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提出三点图像随机在Android的某个位置出现在屏幕上。 我想使这些图像点击。如果你点击它出现计数器将增加一个单个图像。 我怎么做呢?

I want to make three images randomly appear on screen at certain position in android. And I want to make those images clickable. If you click on a single image which is appeared the counter will be increased by one. How do I go about it??

推荐答案

您可以使用下面的code画布绘制图像。

You can draw an image on a Canvas using following code.

Rect dst = new Rect(x, y, x + imageWidth,y + imageHeight);

//enter paint as the last arg to use bitmap filtering
canvas.drawBitmap(myBitmap, null, dst, bitmapFilterSettings);

MYBITMAP是位图,bitmapFilterSettings是的油漆。把这个code在的OnDraw()方法。

myBitmap is a Bitmap, bitmapFilterSettings is a Paint. Place this code in your onDraw() method.

为了随机放置的图像,你必须随机化 X 传递给 DST矩形。为了选择一个随机的形象,你可以把你的位图在列表或一个数组,并使用 nextInt(LISTSIZE) 随机。为了使图像出现和消失随机,使用随机 nextBoolean()方法,只绘制图像如果返回。不要做过于频繁(每隔X帧一次),或者你的形象会闪烁。

In order to place the image randomly, you have to randomize the x and y you pass to the dst Rect. In order to select a random image, you can put you Bitmaps in a List or an array and use the nextInt(listSize) method of Random. In order to make the image appear and disappear randomly, use the nextBoolean() method of Random and only draw the image if it returns true. Do not do this too often (once every X frames), or your image will flicker.

编辑:要做到这一点,你可以声明在活动计数器和决定之间的帧数。您还需要一个布尔字段来切换绘图和关闭。在你的的OnDraw()这可能是这样的:

EDIT : To do this you can declare a counter in the Activity and the number of frames between the decisions. You will also need a boolean field to switch drawing on and off. In your onDraw() it could look like this:

counter++;
if(counter%framesBetweenDecision == 0){
 drawImageFlag = random.nextBoolean();
}
if(drawImageFlag){
//drawImage
}

为了使时间的决定之间少predictable你也可以随机化 timeBetweenDecision
/编辑

To make the times between the decisions less predictable you could also randomize the timeBetweenDecision.
/EDIT

您可以处理触摸事件监听器,调用每次点击随机图像选择。如果你想只有图像部分点击,请检查您的 MotionEvent (可以使用的getX()和getY()以方法)趴在同一的矩形您使用的是使用它的包含(X,Y)方法。

You can handle the touch event in your listener, calling the random image selection on each click. If you want to make only the image part clickable, check the location of your MotionEvent (you can use the getX() and getY() methods) to lie inside the same Rect you are using to draw you image using it's contains(x, y) method.

这是不是实现这一目标的唯一途径,而是一种非常简单的。

This is not the only way to achieve this, but a quite straightforward one.

这篇关于在Android中,如何使图像随机出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆