当前位置: 首页 > 面试题库 >

SVG am示例?

白哲茂
2023-03-14
问题内容

我在用Java和SVG Salamander玩弄,但还不太了解如何将简单的SVG文件渲染为JPanel

有人可以给我一个简单的例子吗?试图按照官方站点上的宽松教程进行操作,但找不到简单的代码来获得更好的理解。


问题答案:

该存储库包含示例代码。如果要使用最新版本,则涉及一些步骤:

  1. 安装Apache Maven。

  2. 将存储库克隆到某个位置:

    mkdir -p $HOME/dev/java/
    

    cd $HOME/dev/java
    git clone https://github.com/blackears/svgSalamander

  3. 更新pom.xml

    cd svgSalamander/svg-core
    

    vi pom.xml

  4. 更改sourcetarget和JDK版本号:

    <maven.compiler.source>1.7</maven.compiler.source>
    

    1.7

    1.7

  5. 保存pom.xml

  6. 使用Maven生成JAR文件: mvn package

  7. 复制target/svgSalamander-1.1.2.jar(确保必须更改版本号)到程序的库目录(例如libs)。

如果您的程序使用Gradle进行构建,请更新依赖项以使用本地JAR文件:

dependencies {
  // SVG
  implementation fileTree(include: ['**/*.jar'], dir: 'libs')
}

如果您使用其他构建系统,则必须相应地更改依赖关系。从那里开始,这是一个使用SVG Salamander缩放和光栅化矢量图形资源文件的类:

import com.kitfox.svg.SVGDiagram;
import com.kitfox.svg.SVGException;
import com.kitfox.svg.SVGUniverse;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.Map;

import static java.awt.RenderingHints.*;
import static java.awt.image.BufferedImage.TYPE_INT_ARGB;

/**
 * Responsible for converting SVG images into rasterized PNG images.
 */
public class SvgRasterizer {
  public final static Map<Object, Object> RENDERING_HINTS = Map.of(
      KEY_ANTIALIASING,
      VALUE_ANTIALIAS_ON,
      KEY_ALPHA_INTERPOLATION,
      VALUE_ALPHA_INTERPOLATION_QUALITY,
      KEY_COLOR_RENDERING,
      VALUE_COLOR_RENDER_QUALITY,
      KEY_DITHERING,
      VALUE_DITHER_DISABLE,
      KEY_FRACTIONALMETRICS,
      VALUE_FRACTIONALMETRICS_ON,
      KEY_INTERPOLATION,
      VALUE_INTERPOLATION_BICUBIC,
      KEY_RENDERING,
      VALUE_RENDER_QUALITY,
      KEY_STROKE_CONTROL,
      VALUE_STROKE_PURE,
      KEY_TEXT_ANTIALIASING,
      VALUE_TEXT_ANTIALIAS_ON
  );

  private final static SVGUniverse sRenderer = new SVGUniverse();

  /**
   * Rasterizes a vector graphic to a given size using a {@link BufferedImage}.
   * The rendering hints are set to produce high quality output.
   *
   * @param path   Fully qualified path to the image resource to rasterize.
   * @param dstDim The output image dimensions.
   * @return The rasterized {@link Image}.
   * @throws SVGException Could not open, read, parse, or render SVG data.
   */
  public Image rasterize( final String path, final Dimension dstDim )
      throws SVGException {
    final var diagram = loadDiagram( path );
    final var wDiagram = diagram.getWidth();
    final var hDiagram = diagram.getHeight();
    final var srcDim = new Dimension( (int) wDiagram, (int) hDiagram );

    final var scaled = fit( srcDim, dstDim );
    final var wScaled = (int) scaled.getWidth();
    final var hScaled = (int) scaled.getHeight();

    final var image = new BufferedImage( wScaled, hScaled, TYPE_INT_ARGB );

    final var g = image.createGraphics();
    g.setRenderingHints( RENDERING_HINTS );

    final var transform = g.getTransform();
    transform.setToScale( wScaled / wDiagram, hScaled / hDiagram );

    g.setTransform( transform );
    diagram.render( g );
    g.dispose();

    return image;
  }

  /**
   * Gets an instance of {@link URL} that references a file in the
   * application's resources.
   *
   * @param path The full path (starting at the root), relative to the
   *             application or JAR file's resources directory.
   * @return A {@link URL} to the file or {@code null} if the path does not
   * point to a resource.
   */
  private URL getResourceUrl( final String path ) {
    return SvgRasterizer.class.getResource( path );
  }

  /**
   * Loads the resource specified by the given path into an instance of
   * {@link SVGDiagram} that can be rasterized into a bitmap format. The
   * {@link SVGUniverse} class will
   *
   * @param path The full path (starting at the root), relative to the
   *             application or JAR file's resources directory.
   * @return An {@link SVGDiagram} that can be rasterized onto a
   * {@link BufferedImage}.
   */
  private SVGDiagram loadDiagram( final String path ) {
    final var url = getResourceUrl( path );
    final var uri = sRenderer.loadSVG( url );
    final var diagram = sRenderer.getDiagram( uri );
    return applySettings( diagram );
  }

  /**
   * Instructs the SVG renderer to rasterize the image even if it would be
   * clipped.
   *
   * @param diagram The {@link SVGDiagram} to render.
   * @return The same instance with ignore clip heuristics set to {@code true}.
   */
  private SVGDiagram applySettings( final SVGDiagram diagram ) {
    diagram.setIgnoringClipHeuristic( true );
    return diagram;
  }

  /**
   * Scales the given source {@link Dimension} to the destination
   * {@link Dimension}, maintaining the aspect ratio with respect to
   * the best fit.
   *
   * @param src The original vector graphic dimensions to change.
   * @param dst The desired image dimensions to scale.
   * @return The given source dimensions scaled to the destination dimensions,
   * maintaining the aspect ratio.
   */
  private Dimension fit( final Dimension src, final Dimension dst ) {
    final var srcWidth = src.getWidth();
    final var srcHeight = src.getHeight();

    // Determine the ratio that will have the best fit.
    final var ratio = Math.min(
        dst.getWidth() / srcWidth, dst.getHeight() / srcHeight
    );

    // Scale both dimensions with respect to the best fit ratio.
    return new Dimension( (int) (srcWidth * ratio), (int) (srcHeight * ratio) );
  }
}

使用SvgRasterizer如下:

final var rasterizer = new SvgRasterizer();
final var image = rasterizer.rasterize( "/images/icon.svg", new Dimension( 200, 200 ) );

该图像可以轻松添加到Swing组件中。例如,以下JComponent是可以与其他任何人一样对待的:

import javax.swing.*;
import java.awt.*;

/**
 * Responsible for drawing an image, which can be changed at any time.
 */
public class ImageComponent extends JComponent {
  /**
   * Mutable image.
   */
  private Image mImage;

  ImageComponent( final Image image ) {
    mImage = image;
  }

  @Override
  public Dimension getPreferredSize() {
    // Race-condition guard.
    final var image = mImage;

    return new Dimension(
        image.getWidth( null ), image.getHeight( null )
    );
  }

  @Override
  protected void paintComponent( final Graphics graphics ) {
    super.paintComponent( graphics );

    final var g = (Graphics2D) graphics.create();
    g.drawImage( mImage, 0, 0, this );
  }

  /**
   * Repaints this component using the given image. This is a mutable
   * operation that changes the internal {@link Image} instance.
   *
   * @param image The new image to use for painting.
   */
  public void redraw( final Image image ) {
    mImage = image;
    repaint();
  }
}


 类似资料:
  • Composite Images watermark(['/img/shepherd.jpg', '/img/logo.png']) .image(watermark.image.lowerRight()) .then(function (img) { document.getElementById('composite-image').appendChild(img); }); Al

  • 示例的Python源代码或者交互界面都可以使用标准reST模块实现.在正常段落后面跟着 :: 开始,再加上适当缩进. 交互界面需包含提示及Python代码的输出. 交互界面没有特别的标记. 在最后一行输入或输出之后,不应出现空的提示; 这是一个什么都不做的例子: >>> 1 + 1 2 >>> 语法高亮显示由 Pygments (如果安装) 优雅的显示: 每个源文件都有高亮语言”highlight

  • Redux 源码 中同时包含了一些示例。这些示例中的大多数也在CodeSandbox上,这是一个在线编辑器,可让您在线测试示例。 原生版 Counter 运行 Counter Vanilla 示例: git clone https://github.com/reactjs/redux.git cd redux/examples/counter-vanilla open index.html 该示

  • 这是一些 Mithril 的示例: Animation DBMonster Markdown Editor SVG: Clock, Ring, Tiger ThreadItJS TodoMVC

  • 已经有超过50,000本图书使用GitBook.com发布。 文档 DuckDuckHack 文档 by DuckDuckGo Loomio Handbook and guide to using Loomio both by Loomio Enspiral Handbook by Enspiral Webmagic开发文档 by https://github.com/code4craft/web

  • 这里列出了所有示例: adc_vol_sample.c dynmem_sample.c event_sample.c httpclient_sample.c hwtimer_sample.c i2c_aht10_sample.c idlehook_sample.c interrupt_sample.c iwdg_sample.c led_blink_sample.c mailbox_sample.

  • 下面的例子说明了部署描述文件模式中列出的定义的用法。 一个简单的例子 CODE EXAMPLE 14-1 Basic Deployment Descriptor Example <?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://

  • 计算变量 首先,让我们从一些必要的代码开始。 这个例子的目的是如果条件满足,将 a 和 b 计算后的值绑定到 c 上。 下面就是必要的代码示例: // this is standard imperative code var c: String var a = 1 // this will only assign the value `1` to `a` once var b = 2