使用AffineTransform将Shape缩放/转换为给定的Rectangle

时间:2010-10-01 21:18:16

标签: java graphics drawing shapes affinetransform

我正在尝试使用 AffineTransform 缩放/翻译java.awt。 Shape ,以便在定义的边界矩形中绘制它。

此外,我想在具有“缩放”参数的绘图区域中绘制它。

我尝试了各种各样的AffineTransform连接,但我找不到正确的序列。例如,以下解决方案是错误的:

double zoom=(...);/* current zoom */
Rectangle2D viewRect=(...)/** the rectangle where we want to paint the shape */
Shape shape=(...)/* the original shape that should fit in the rectangle viewRect */
Rectangle2D bounds=shape.getBounds2D();

double ratioW=(viewRect.getWidth()/bounds.getWidth());
double ratioH=(viewRect.getHeight()/bounds.getHeight());


AffineTransform transforms[]=
    {
    AffineTransform.getScaleInstance(zoom, zoom),
    AffineTransform.getTranslateInstance(-bounds.getX(),-bounds.getY()),
    AffineTransform.getTranslateInstance(viewRect.getX(),viewRect.getY()),
    AffineTransform.getScaleInstance(ratioW, ratioH)
    };


AffineTransform tr=new AffineTransform();
for(int i=0;i< transforms.length;++i)
    {
    tr.concatenate(transforms[i]);
    }

Shape shape2=tr.createTransformedShape(shape);
graphics2D.draw(shape2);

关于正确的AffineTransform的任何想法?

非常感谢

皮尔

2 个答案:

答案 0 :(得分:7)

请注意,AffineTransform转换以“最常用的方式”连接在一起,可以在, first-out 顺序中将其视为 last。效果可以在example中看到。给定下面的序列,首先旋转结果Shape,然后缩放,最后翻译。

at.translate(SIZE/2, SIZE/2);
at.scale(60, 60);
at.rotate(Math.PI/4);
return at.createTransformedShape(...);

答案 1 :(得分:1)

受到trashgod答案的启发,正确的顺序是:

AffineTransform transforms[]=
{
AffineTransform.getScaleInstance(zoom, zoom),
AffineTransform.getTranslateInstance(viewRect.getX(),viewRect.getY()),
AffineTransform.getScaleInstance(ratioW, ratioH),
AffineTransform.getTranslateInstance(-bounds.getX(),-bounds.getY())
};



AffineTransform tr=new AffineTransform();
for(int i=0;i< transforms.length;++i)
 {
 tr.concatenate(transforms[i]);
 }