2016-05-30 156 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