java 使用 AffineTransform 将形状缩放/转换为给定的矩形
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3843105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scaling/Translating a Shape to a given Rectangle using AffineTransform
提问by Pierre
I'm trying to scale/translate a java.awt.Shapewith AffineTransformin order to draw it in a defined bounding Rectangle.
我正在尝试缩放/翻译 java.awt。使用AffineTransform塑造形状,以便在定义的边界矩形中绘制它。
Moreover, I want to paint it in a drawing Area having a 'zoom' parameter.
此外,我想在具有“缩放”参数的绘图区域中绘制它。
I tried various concatenations of AffineTransform but I couldn't find the correct sequence. For example, the following solution was wrong:
我尝试了 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);
Any idea about the correct AffineTransform ?
知道正确的 AffineTransform 吗?
Many thanks
非常感谢
Pierre
皮埃尔
回答by trashgod
Note that AffineTransform
transformations are concatenated "in the most commonly useful way", which may be regarded as last in, first-outorder. The effect can be seen in this example. Given the sequence below, the resulting Shape
is first rotated, then scaled and finally translated.
需要注意的是AffineTransform
转换串接“中最常用的方式”,这可以看作是最后的,先出的顺序。在这个例子中可以看到效果。给定下面的序列,结果Shape
首先旋转,然后缩放,最后平移。
at.translate(SIZE/2, SIZE/2);
at.scale(60, 60);
at.rotate(Math.PI/4);
return at.createTransformedShape(...);
回答by Pierre
Inspired by trashgod's answer, the correct sequence was:
受垃圾神的回答启发,正确的顺序是:
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]);
}