2016-05-30 131 views
0

假設我有矩形選擇(x,y,寬度和高度)。是否可以從Java SWT中的圖像獲取子圖像?我有ImageCanvas。用戶選擇圖像的一部分。我想用用戶選擇替換圖像。SWT:從圖像中獲取子圖像

我無法找到實現此目的的方法。是我使用Canvas的問題嗎?

更新: 這是我目前使用drawImage的方法。我想這是一個黑客攻擊的一位,因爲我沒有得到的圖像的子集,並創建一個新的形象 - 我只是繪製圖像的一部分:

  int minX = Math.min(startX, endX); 
      int minY = Math.min(startY, endY); 

      int maxX = Math.max(startX, endX); 
      int maxY = Math.max(startY, endY); 

      int width = maxX - minX; 
      int height = maxY - minY; 
      gc.drawImage(image, minX, minY, width, height, image.getBounds().x, 
      image.getBounds().y, image.getBounds().width, image.getBounds().height); 

回答

2

您可以使用該方法Canvas#copyArea(Image, int, int)把剛纔複製您感興趣的區域是給定的Image。然後設置ImageLabel

private static boolean drag = false; 

private static int xStart; 
private static int yStart; 

private static int xEnd; 
private static int yEnd; 
private static Image outputImage = null; 

public static void main(String[] args) 
{ 
    final Display display = new Display(); 
    final Shell shell = new Shell(display); 
    shell.setText("Stackoverflow"); 
    shell.setLayout(new FillLayout()); 

    Image inputImage = new Image(display, "baz.png"); 
    Label output = new Label(shell, SWT.NONE); 

    Canvas canvas = new Canvas(shell, SWT.DOUBLE_BUFFERED); 

    canvas.addListener(SWT.Paint, e -> e.gc.drawImage(inputImage, 0, 0)); 

    canvas.addListener(SWT.MouseDown, e -> { 
     xStart = e.x; 
     yStart = e.y; 
     drag = true; 
    }); 

    canvas.addListener(SWT.MouseUp, e -> { 
     drag = false; 

     int x = Math.min(xStart, xEnd); 
     int y = Math.min(yStart, yEnd); 

     if (outputImage != null && !outputImage.isDisposed()) 
      outputImage.dispose(); 

     outputImage = new Image(display, new Rectangle(x, y, Math.abs(xEnd - xStart), Math.abs(yEnd - yStart))); 
     GC gc = new GC(inputImage); 

     gc.copyArea(outputImage, x, y); 
     output.setImage(outputImage); 

     gc.dispose(); 
    }); 
    canvas.addListener(SWT.MouseExit, e -> drag = false); 

    canvas.addListener(SWT.MouseMove, e -> { 
     if (drag) 
     { 
      xEnd = e.x; 
      yEnd = e.y; 
     } 
    }); 

    shell.pack(); 
    shell.open(); 

    while (!shell.isDisposed()) 
    { 
     if (!display.readAndDispatch()) 
      display.sleep(); 
    } 
    display.dispose(); 
    inputImage.dispose(); 
    if (outputImage != null && !outputImage.isDisposed()) 
     outputImage.dispose(); 
} 

是這樣的:

enter image description here