gpt4 book ai didi

java - SWT:从图像中获取子图像

转载 作者:行者123 更新时间:2023-12-02 03:35:18 27 4
gpt4 key购买 nike

假设我有矩形选择(x、y、宽度和高度)。是否可以从 Java SWT 中的图像获取子图像?

我在 Canvas 上有一个Image。用户选择图像的一部分。我想用用户选择替换图像。

我找不到实现此目标的方法。问题出在我使用 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 );

最佳答案

您可以使用方法 Canvas#copyArea(Image, int, int) 将您感兴趣的区域复制到给定的 Image。然后将Image设置为Label:

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

关于java - SWT:从图像中获取子图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37520572/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com