gpt4 book ai didi

java swt 图像(图像数据)旋转

转载 作者:行者123 更新时间:2023-12-03 18:23:28 26 4
gpt4 key购买 nike

我正在尝试做一个简单的程序,我可以在其中添加一些 png 到 Canvas 。其中一个选项是旋转选定的 png。我有旋转问题。当我使用 Transformation 时,它会旋转 Canvas 上的所有内容。我只创建了旋转 90' 或翻转的示例,但我想旋转任何角度。

我也曾尝试将 swt 图像转换为 bufferedimage,然后旋转,然后将 bufferedimage 转换为 swt 图像并绘制它,但速度非常慢,并且在透明度方面存在一些问题。

我将不胜感激 - 我想通过图像中心旋转。对于 drawig,我使用 GC 和 Canvas - new GC(canvas);


编辑:我仍然无法按图像中心旋转:

gc.setAdvanced(true);
if (!gc.getAdvanced()) {
gc.drawText("Advanced graphics not supported", 30, 30, true);
return;
}

Transform oldTransform = new Transform(gc.getDevice());
gc.getTransform(oldTransform);

Transform transform = new Transform(GCController.getCanvas().getDisplay());
transform.translate(width/2, height/2);
transform.rotate(rotation);
gc.setTransform(transform);
gc.drawImage(image, x, y);

gc.setTransform(oldTransform);

transform.dispose();

最佳答案

你必须使用矩阵变换。看看this SWT 片段。作为引用,我以 15 度为例(接近尾声)。

import org.eclipse.swt.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;

public class ImageTest {
public static void main(String[] args) {
final Display display = new Display();

final Image image = new Image(display,"next.png");


final Rectangle rect = image.getBounds();
Shell shell = new Shell(display);
shell.setText("Matrix Tranformations");
shell.setLayout(new FillLayout());
final Canvas canvas = new Canvas(shell, SWT.DOUBLE_BUFFERED);
canvas.addPaintListener(new PaintListener () {
public void paintControl(PaintEvent e) {
GC gc = e.gc;
gc.setAdvanced(true);
if (!gc.getAdvanced()){
gc.drawText("Advanced graphics not supported", 30, 30, true);
return;
}

// Original image
int x = 30, y = 30;
gc.drawImage(image, x, y);
x += rect.width + 30;

Transform transform = new Transform(display);

// Note that the tranform is applied to the whole GC therefore
// the coordinates need to be adjusted too.

// Reflect around the y axis.
transform.setElements(-1, 0, 0, 1, 0 ,0);
gc.setTransform(transform);
gc.drawImage(image, -1*x-rect.width, y);



// Rotate by 45 degrees
float cos45 = (float)Math.cos(Math.PI/4);
float sin45 = (float)Math.sin(Math.PI/4);
transform.setElements(cos45, sin45, -sin45, cos45, 0, 0);
gc.setTransform(transform);
gc.drawImage(image, x , y);

float cos15 = (float)Math.cos(Math.PI/12);
float sin15 = (float)Math.sin(Math.PI/12);
transform.setElements(cos15, sin15, -sin15, cos15, 0, 0);
gc.setTransform(transform);
gc.drawImage(image, x+rect.width/2 , y+rect.height/2);

transform.dispose();
}
});

shell.setSize(350, 550);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
image.dispose();
display.dispose();
}
}

>>输出

enter image description here

关于java swt 图像(图像数据)旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5900199/

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