我有一個方法需要一個字符串和一個整數作爲參數。該方法基本上返回原始圖像的較小的裁剪部分。該字符串是路徑和我在一個switch語句中使用的整數,用於我需要的特定部分,我嘗試了打印輸出,但無論出於何種原因,x和y保持在0,即使我知道我正在獲取高度的值和寬度。返回圖標不能正常工作的方法
private Icon extractIcon(String path, int i){
// reads the image into a BufferedImage object
BufferedImage image=null;
try{
image = ImageIO.read(new File(path));
}
catch(IOException e){
System.err.println("Image not found");
System.exit(1);
}
height = image.getHeight();
width = image.getWidth();
// allocates another BufferedImage object whose size is
// the same as the one of the wanted icon
BufferedImage part = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
switch(i){
case 1:
x = 0;
y = 0;
break;
case 2:
x = width*(1/3);
y = 0;
break;
case 3:
x = width*(2/3);
y = 0;
break;
case 4:
x = 0;
y = height*(1/3);
break;
case 5:
x=width*(1/3);
y=height*(1/3);
break;
case 6:
x=width*(2/3);
y=height*(1/3);
break;
case 7:
x = 0;
y=height*(2/3);
break;
case 8:
x = width*(1/3);
y = height*(2/3);
break;
}
//Intializes leftTopX and leftTopY for each button after switch
leftTopX = width*(1/3)+x;
leftTopY = height*(1/3)+y;
// copies the data from "image" to "part"
System.out.println(x + " xy " + y);
System.out.println(leftTopY + " leftxy " + leftTopX);
for(;x<width;x++){
for(;y<height;y++){
part.setRGB(x,y, image.getRGB(x+leftTopX, y+leftTopY));
}
}
// creates an icon whose content is already in "part"
ImageIcon icon = new ImageIcon();
icon.setImage(part);
// returns to the caller
return icon;
}
噢,親愛的主,你是對的... – user111702 2014-10-06 22:24:54
是的,我做過這一百萬次;) – MadProgrammer 2014-10-06 22:25:34
總是與整數除法哈哈,非常感謝! – user111702 2014-10-06 22:31:41