2012-02-23 86 views
1

我已经阅读了一张图片,并且想要随机设置int xint y的值,但分别只能达到图像的宽度和高度,并且不能低于0,0,因此它们不会超过图像的边界。Java - 将整数值设置为最大图像大小

事情是这样的:

read image //I have this already 
assign random value to int x up to maxWidth of image but >= 0 
assign random value to int y up to maxHeight of image but >= 0 
end 

通常情况下,几乎所有我一起工作的图像是约424 X 424

我最终寻求与价值观,如落得:

int x = 325; 
int y = 10; 

int x = 424 
int y = 351 

int x = 109 
int y = 230 

每次我运行该代码,为xy值将随机如之前被重新分配。

这可能吗?

+0

你有没有尝试使用例如['Random'](http://docs.oracle.com/javase/6/docs/api/java/util/Random.html)? – 2012-02-23 00:54:52

+0

@Mick:你是什么意思*“每次运行代码时,x和y的值都将像以前一样随机重新分配。”*?这是“以前”的**部分,很奇怪。你想要它是随机的,但可重现吗?如果是这样的话,你想为你的PRNG使用一个固定的种子。例如,而不是*新的随机(System.currentTimeMillis())*,你会做*新的随机(42)*。 – TacticalCoder 2012-02-23 01:03:05

+0

是的,我希望每次程序运行时赋予'x'和'y'的新值,它们> = 0,0且<= maxHeight&maxWidth。 – MusTheDataGuy 2012-02-23 01:09:10

回答

1

你想要的东西,如:

import java.util.Random; 

..stuff.. 

// create a random instance - you only need one of these 
Random r=new Random(); 

..stuff.. 

// create a random co-ordinate within the image rectangle 
int x=r.nextInt(image.getWidth()); 
int y=r.nextInt(image.getHeight()); 
1

不知道如果你问如何获取图像的宽度和高度,但如果不是,那么只需获得0和每个图像尺寸之间的随机int。

final int width, height; 
Random rand = new Random(System.currentTimeMillis()); 
final int x = rand.nextInt(width); 
final int y = rand.nextInt(height); 
+0

我能够获得图像的宽度和高度;我只需要为with和height生成高达最大值的值,但不能小于0。 – MusTheDataGuy 2012-02-23 00:56:08