本文介绍了使用 AffineTransform 将形状缩放/转换为给定的矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 AffineTransform 缩放/平移 java.awt.Shape,以便将其绘制在定义的边界矩形中.

I'm trying to scale/translate a java.awt.Shape with AffineTransform in order to draw it in a defined bounding Rectangle.

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

Moreover, I want to paint it in a drawing Area having a 'zoom' parameter.

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

I tried various concatenations of AffineTransform but I couldn't find the correct sequence. For example, the following solution was wrong:

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 吗?

Any idea about the correct AffineTransform ?

非常感谢

皮埃尔

推荐答案

请注意 AffineTransform 转换以最常用的方式"连接起来,这可以被视为 last in, 先出顺序.在这个示例中可以看到效果.给定以下序列,生成的 Shape 首先旋转,然后缩放,最后平移.

Note that AffineTransform transformations are concatenated "in the most commonly useful way", which may be regarded as last in, first-out order. The effect can be seen in this example. Given the sequence below, the resulting Shape is first rotated, then scaled and finally translated.

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

这篇关于使用 AffineTransform 将形状缩放/转换为给定的矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-03 09:35