【问题标题】:Java: drawing scaled objects (buffered image and vector graphics)Java:绘制缩放对象(缓冲图像和矢量图形)
【发布时间】:2016-12-04 10:09:25
【问题描述】:

我想绘制包含光栅和矢量数据的缩放对象。目前,我正在绘制一个缩放的 Graphics2D 对象

protected void paintComponent(Graphics g) {

    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g.create();

    //Get transformation, apply scale and shifts
    at = g2d.getTransform();
    at.translate(x, y);
    at.scale(zoom, zoom);      

    //Transform Graphics2D object  
    g2d.setTransform(at);

    //Draw buffered image into the transformed object
    g2d.drawImage(img, 0, 0, this);

    //Draw line into transformed Graphics2D object
    Line2D.Double line = new Line2D.Double();
    line.x1 = (int)p1.getX();
    line.y1 = (int)p1.getY();
    line.x2 = (int)p2.getX();
    line.y2 = (int)p2.getY();

    g2d.draw(line);

    g2d.dispose();
}

不幸的是,这种方法有一些缺点(影响笔画宽度,缩放图像的质量较差)。

相反,我想绘制缩放的对象。对于矢量数据,方法很简单:

protected void paintComponent(Graphics g) {

    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g.create();

    //Update affine transformation
    at = AffineTransform.getTranslateInstance(x, y);
    at = AffineTransform.getScaleInstance(zoom, zoom);

    //Transform line and draw
    Line2D.Double line = new Line2D.Double();
    line.x1 = (int)p1.getX();
    line.y1 = (int)p1.getY();
    line.x2 = (int)p2.getX();
    line.y2 = (int)p2.getY();

    g2d.draw(at.createTransformedShape((Shape)line));

    //Transform buffered image and draw ???
    g2d.draw(at.createTransformedShape((Shape)img));  //Error

    g2d.dispose();
}

但是,如何在不重新缩放 Graphics2D 对象的情况下将转换应用于缓冲图像?这种方法行不通

g2d.draw(at.createTransformedShape((Shape)img)); 

因为光栅图像不能理解为矢量形状...

感谢您的帮助。

【问题讨论】:

  • 您可以使用g2d.transform(at); g2d.drawImage(img, 0, 0, null);,而不是标有//Error 的行。如果您有质量问题,请考虑更改 Graphics2D 的渲染提示。

标签: java transformation bufferedimage vector-graphics rescale


【解决方案1】:

一种可能的解决方案可能表示栅格的仿射变换:

//Update affine transformation
at = AffineTransform.getTranslateInstance(x, y);
at = AffineTransform.getScaleInstance(zoom, zoom);

at.translate(x, y);
at.scale(zoom, zoom);      

//Create affine transformation
AffineTransformOp op = new AffineTransformOp(at,  AffineTransformOp.TYPE_NEAREST_NEIGHBOR);

//Apply transformation
BufferedImage img2 = op.filter(img, null);

//Draw image
g2d.drawImage(img2, 0, 0, this);

不幸的是,这种方法不适合缩放操作;它的计算成本更高。对于栅格数据(JPG,5000 x 7000 pix),一个简单的双线性插值

AffineTransformOp op = new AffineTransformOp(at,  AffineTransformOp.TYPE_BILINEAR);

大约需要 1.5 秒...相反,使用缩放的 Graphics2D 对象明显更快(

在我看来,将对象与栅格数据一起重新缩放比重新缩放 Graphics2D 对象要慢......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-17
    • 2018-01-12
    • 1970-01-01
    • 2012-04-29
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多