经过反复试验,我设法得到了一些应该接近你想要的东西。
public class CopyArea {
public static void main( String[] args ) {
CopyArea copyArea = new CopyArea();
copyArea.create();
copyArea.run();
}
private Display display;
private Image sourceImage;
private Point canvasSize;
private Shell shell;
private Canvas source;
private Canvas destination;
private Point snippetOrigin;
private Image snippet;
CopyArea() {
display = new Display();
sourceImage = new Image( display, getClass().getResourceAsStream( "mona-lisa.jpeg" ) );
canvasSize = new Point( sourceImage.getBounds().width, sourceImage.getBounds().height );
shell = new Shell( display );
source = new Canvas( shell, SWT.NONE );
destination = new Canvas( shell, SWT.NONE );
}
void create() {
shell.setLayout( new RowLayout() );
source.setLayoutData( new RowData( canvasSize ) );
source.addPaintListener( new PaintListener() {
@Override
public void paintControl( PaintEvent event ) {
event.gc.drawImage( sourceImage, 0, 0 );
if( snippetOrigin != null ) {
snippet = new Image( display, 40, 40 );
event.gc.copyArea( snippet, snippetOrigin.x, snippetOrigin.y );
destination.redraw();
snippetOrigin = null;
}
}
} );
source.addMouseListener( new MouseAdapter() {
@Override
public void mouseDown( MouseEvent event ) {
snippetOrigin = new Point( event.x, event.y );
source.redraw();
}
} );
destination.setLayoutData( new RowData( canvasSize ) );
destination.addPaintListener( new PaintListener() {
@Override
public void paintControl( PaintEvent event ) {
event.gc.setBackground( display.getSystemColor( SWT.COLOR_WHITE ) );
event.gc.fillRectangle( event.gc.getClipping() );
if( snippet != null ) {
event.gc.drawImage( snippet, 0, 0 );
}
}
} );
}
void run() {
shell.pack();
shell.open();
while( !shell.isDisposed() ) {
if( !display.readAndDispatch() )
display.sleep();
}
display.dispose();
}
}
sourceImage 只是您的绘图代码的占位符。 source Canvas 侦听鼠标按下事件,然后将其客户端的 40x40 sn-p 绘制到 destination Canvas。请注意,我在这两种情况下都使用了 Canvas,但 Canvas 和 Composite 也应该可以工作。
它的工作原理如下:鼠标侦听器将鼠标位置存储到snippetOrigin 并触发source 的重绘。 source 的绘图侦听器在请求时截取刚刚绘制的部分屏幕截图 (snippetOrigin != null),然后强制 destination 重新绘制自身。 destination simple 的paint-listener 绘制snippet 图像(如果有)。
deos 代码尚未正确剪辑复制的图像。如果你在source画布的右下角按下鼠标,也会复制一些shell的修剪。
为简洁起见,代码不会在重用 snippet 图像之前对其进行处理(并且可能存在其他泄漏)。
如果您拥有绘制等效于 source 画布的绘图代码,我宁愿重构它以便可以绘制任意部分,然后使用适当的参数调用代码以在 destination 小部件上绘制。