2012-02-23 57 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