如何在Java中获取CGAffineTransform的Shape旋转图像

问题描述 投票:0回答:3

我能够旋转图像。这非常有效。但是,我希望能够对结果图像的Shape / Polygon进行extraxt,以便在鼠标移动到旋转的图像上时可以使用它来捕获鼠标事件。

她的代码:

private Shape imageShape;

private Image rotateFilter(Image img, int degrees) {
    BufferedImage sourceImage = (BufferedImage)img;

    double radians = Math.toRadians(degrees);
    double cos = Math.abs(Math.cos(radians));
    double sin = Math.abs(Math.sin(radians));

    int width = sourceImage.getWidth();
    int height = sourceImage.getHeight();

    int w = (int) Math.floor(width * cos + height * sin);
    int h = (int) Math.floor(width * sin + height * cos);

    int x = (w - width) / 2;
    int y = (h - height) / 2;

    BufferedImage destImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);        
    Graphics2D g2d = destImage.createGraphics();

    AffineTransform at = new AffineTransform();
    at.rotate(radians, x + (width / 2), y + (height / 2));
    at.translate(x, y);

以某种方式得到形状/多边形(imageShape)g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2d.drawRenderedImage(sourceImage,at); g2d.dispose(); return destImage; }

public void mouseEntered(MouseEvent e) {
    int mx = e.getX();
    int my = e.getY();
    return imageShape.contains(mx, my);
}
java image rotation shapes
3个回答
0
投票

不幸的是,没有简单的方法。如果旋转图像,仍会得到一个矩形,图像会旋转到它上面。我能够绕过它的唯一方法是使用数学管理4个角落,但当然数学与AffineTransform旋转完全不同。

我想要做的是旋转图像并对其应用一个形状,以便我可以使用带有鼠标x / y的contains()。我只希望鼠标在鼠标悬停在图像上时接收事件,即使它被旋转。


0
投票

有多种方法可以做到这一点 - 除了你提出的直接数学,你必须应用于转换矩阵以及同一方面:

a)使用点并转换这些:

    AffineTransform at=AffineTransform.getRotateInstance(....);
    Point p=new Point(x, y);
    at.transform(p, p);

这将转换点p并将结果存储到自身,因此p将改变 - 您可以使用另一个点来存储新坐标。

应用于四个点然后创建多边形

Polygon pl=new Polygon();
for(i=0; i<points.length; i+++) pl.addPoint(points[i].x, points[i].y);

Polygon具有contains()方法。

b)从原始图像创建多边形(或矩形)

Polygon pl=new Polygon();
pl.addPoint(0, 0);
pl.addPoint(im.getWidth()-1, 0);
pl.addPoint(im.getWidth()-1, im.getHeight()-1);
pl.addPoint(0, im.getHeight()-1);

要么

Rectangle r=new Rectangle(0, 0, im.getWidth(), im.getHeight());

然后用

  AffineTransform at=new AffineTransform(.....);
  Shape sh=at.createTransformedShape(pl);

并将sh作为新形状。这个东西并不总是准确地工作(我的意思是整个形状,边界等),但如果你正在寻找它,这很方便。


0
投票

是的,我几乎完全使用了你的选项B.我这样做的方式是存储两个矩形。一个用于存储旋转/变换图像的x,y,w,h,另一个用于存储一组原始图像x,y,w,h。后一个矩形不会改变(好吧,至少在我缩放之前,在这种情况下这个矩形会更新)。由于后者没有改变,我使用它来记录“真实”图像而不是转换后的图像。所以我做的事情仿真转换图像,然后像你建议的那样构建一个多边形,然后使用createTrasformedShape来获取形状。因此,钉在钉子上。它工作得很好。有点慢,但非常准确。谢谢。

© www.soinside.com 2019 - 2024. All rights reserved.